BAcevedo
BAcevedo

Reputation: 127

How to read content from plain text remote file with objective-c

I want to read a list (in plain text) from a remote file line by line. I have found some answers but they're not the ones I'm looking for.

p.s. I've been programing in objective-c and developing in iOS for about 2 months, I'm a rookie i might not understand or recognize some terms. Please answer like you are talking to a beginner.

Upvotes: 1

Views: 3173

Answers (3)

user3386109
user3386109

Reputation: 34829

There are three steps involved in loading a file

  1. create the object that specifies the location of the file
  2. call the appropriate NSString class method to load the file into a string
  3. handle the error if the file is not found

In step 1, you need to either create an NSString with the full path to the file in the file system, or you need to create an NSURL with the network location of the file. In the example below, the code creates an NSURL since your file is on the network.

In step 2, use the stringWithContentsOfFile method to load a file from the file system, or the stringWithContentsOfURL method to load a file from the network. In either case, you can specify the file encoding, or ask iOS to auto-detect the file encoding. The code below auto detects while loading from the network.

In step 3, the code below dumps the file to the debug console if successful or dumps the error object to the console on failure.

Missing from this code is multithreading. The code will block until the file is loaded. Running the code on a background thread, and properly notifying the main thread when the download is complete, is left as an exercise for the reader.

NSURL *url = [NSURL URLWithString:@"www.example.com/somefile.txt"];
NSStringEncoding encoding;
NSError *error;
NSString *str = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error];
if ( str )
    NSLog( @"%@", str );
else
    NSLog( @"%@", error );

Upvotes: 0

Guillaume Algis
Guillaume Algis

Reputation: 11016

To load the remote txt file, you should take a look at NSURLConnection or AFNetworking (there are other possibilities, these two are probably the most common).

You will then get the content of the file. Depending on what you intend to do with it, you may have to parse it, either with something as simple as -[NSString componentsSeparatedByString:] or with something a bit more powerful like NSScanner.

Upvotes: 0

mhrrt
mhrrt

Reputation: 977

If i am not wrong you just want to read a text from remote file, so here it is.

NSString * result = NULL;
NSError *err = nil;
NSURL * urlToRequest = [NSURL   URLWithString:@"YOUR_REMOTE_FILE_URL"];//like "http://www.example.org/abc.txt"
if(urlToRequest)
{
    result = [NSString stringWithContentsOfURL: urlToRequest
                                      encoding:NSUTF8StringEncoding error:&err];
}

if(!err){
    NSLog(@"Result::%@",result);
}

Upvotes: 5

Related Questions