Question

Im kind of new to Objective C and I wondering if anyone could help me (or point me to a tutorial) to download a .plist file to my iOS app then read it, I need the file to be downloaded Asynchronously so it doesn't pause the app while downloading.

The current code I'm using is:

//UERootArray = [[NSArray alloc] initWithContentsOfURL:[NSURL URLWithString:@"file to url"]];

Ive looked a lot online and cannot find any tutorials, I know this is simple but your help would be much appreciated. Thanks.

Was it helpful?

Solution

You can use NSURLConnection for achieving this.

or

You can simply use GCD for this, like:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
   UERootArray = [[NSArray alloc] initWithContentsOfURL:[NSURL URLWithString:@"file to url"]];
});

OTHER TIPS

If you wanted to know that your App has finished downloading and after that you wanted to perform some action then in that case, you need to write your own custom delegate which will update when app has finished downloading. But for asynchronous downloading you use GCD as mentioned by Midhun. Refer this How to write Custom Delegate?

Below is the sketch of the implementation using NSURLConnection. Note that completionHandler will be called when your download completes (with either OK or an error), and you can call function that processes Array from there.

Other answers provided here are also valid and it's ultimately your call to figure out which fits your case best.

NSURLRequest* theRequest = [NSURL URLWithString:@"file to url"];
[NSURLConnection sendAsynchronousRequest:theRequest
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse* theResponse, NSData* theData, NSError* theError) {
    if (theData) {
        NSError* err = nil;
        id Array [NSPropertyListSerialization propertyListWithData:theData 
                                                           options:NSPropertyListImmutable
                                                            format:NULL
                                                              error:&err];
        if ([Array isKindOfClass:[NSArray class]) {
            // Do whatever you need with downloaded array
        } else {
            // Error -- wrong data, check err
        }
    } else {
        // Error while downloading, check theError
    }
}];

Try this for Download with completion hander.

 NSMutableURLRequest *request=[[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:@"http://"]];


dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
   [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue]  completionHandler:^(NSURLResponse *response,NSData *data,NSError *error)
     {

    //do your stuff when downloading complete..
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top