How to read an NSArray from a URL without blocking the app

Developing applications that display data from the network often presents a challenge: how to read data from an external file. Parsing XML in Objective-C is quite resource-intensive, so it’s worth considering whether a simpler solution might be to create a .plist file (Property list) on the server and download that file format to the application. It’s worth noting that reading an NSArray or NSDictionary from a file is just two lines:

NSURL *myUrl = [NSURL URLWithString:@"https://dev.orpi.pl/someexamplefile.plist"]; NSArray *myChartData = [NSArray arrayWithContentsOfURL:myUrl];

However, a problem arises if the device on which we try to read the file does not have an internet connection. In this case, myChartData will return nil, but the device will “hang” until a timeout is received.”

Solution: Display a loader (discussed in the next article) and use NSURLConnection

NSURL *myUrl = [NSURL URLWithString:stringUrl];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:myUrl];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *receivedData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];

After this operation, we receive the ‘receivedData’ object and, in case of failure, the ‘error’ object

Now comes the “most difficult” part – loading NSData into NSArray
There are several methods – I’ll demonstrate one of them

if (error == nil) {
    NSString *listFile = [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding];
    NSArray *myChartData = [listFile propertyList];
} else {
    // Error handling, e.g., alert:
    NSString *alertString = @"No internet connection or server not found.";
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:alertString
                                                    message:nil
                                                   delegate:nil
                                             cancelButtonTitle:nil
                                             otherButtonTitles:@"OK", nil];
    [alert show];
    [alertString release];
}

The presented method has a drawback. If we read incorrect data, the application may receive an empty object.
I will soon describe another method that allows us to check if the received object is of type NSArray;