Downloading a text file from internet to iPhone

Discussion in 'iPhone/iPad Programming' started by russellelly, Nov 2, 2008.

  1. macrumors regular

    Joined:
    Jun 23, 2006
    Location:
    Glasgow, UK
    #1
    I appreciate this is probably really easy. I've spent ages trying, but getting nowhere.

    I'm trying to just download the contents of a webpage (http://xmltv.radiotimes.com/xmltv/channels.dat) to an NSString (eventually split, but the whole page as one string will do for now). I've looked at the NSURL class, but anything I try results in the iPhone (sim) crashing, or an uncaught exception warning.

    Again, sorry for (yet another) fairly noob question - new to Obj-C and iPhone :)
     
  2. macrumors newbie

    Joined:
    Jan 17, 2008
    #2
    I actually experimented with this exact thing this morning. Here's code that works for me...

    Code:
    NSString *fileContents = [NSString stringWithContentsOfURL:
                                       [[NSURL alloc] initWithString:
                                               @"http://example.com/textfile"]];
    
     
  3. thread starter macrumors regular

    Joined:
    Jun 23, 2006
    Location:
    Glasgow, UK
    #3
    Thanks - that does the trick :) Finally getting somewhere with my first app! Was having trouble having it as a separate method and possibly allocating the memory twice. Been treated to good old GC'ed Java for too long!
     
  4. macrumors member

    Joined:
    Mar 16, 2008
    Location:
    Austin, Texas
    #4
    Be careful with synchronous URL requests on the main thread, they will lock the UI. NSURLConnection's initWithRequest will do it asynchronously. With the asynchronous route, you'll append received data to a mutable data object. However, this will eventually require a conversion to string for you, so at some point you'll still have duplicated your data, if only temporarily.
     

Share This Page