Synchronous download in iOS application development

The download should happen synchronously because there is no need for the application to move on before the data which should be displayed is received. However, asynchronous downloads may be done in iOS version 5 there is no need for doing the download asynchronous.
1 answer

iOS application using synchronous downloads

Synchronous downloads allow to request data from the internet, wait until that data is received, and then move on to the next step in your application.
I will describe the process with some attached code. The code is both synchronous and blocking so the method will not return before the data is received.

- (SimpleKML *) getData: (NSURL *) url
{
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSURLResponse *response;
NSError *error;

success = NO;

SimpleKML* kmlData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];

//if there is no kmlData the download failed
if (!kmlData)
{
[self log:@"Download error: %@", [error localizedFailureReason]];
return;
}

if ((response.expectedContentLength == NSURLResponseUnknownLength) ||
(response.expectedContentLength < 0))
{
[self log:@"Download error."];
return;
}

if (![response.suggestedFilename isEqualToString:url.path.lastPathComponent])
{
[self log:@"Name mismatch. Probably carrier error page"];
return;
}

if (response.expectedContentLength != result.length)
{
[self log:@"Got %d bytes, expected %d", result.length, response.expectedContentLength];
return;
}

success = YES;
[self log:@"Read %d bytes", result.length];
[result writeToFile:DEST_PATH atomically:YES];
[self log:@"Data written to file: %@.", DEST_PATH];
[self log:@"Response suggested file name: %@", response.suggestedFilename];
[self log:@"Elapsed time: %0.2f seconds.", [[NSDate date] timeIntervalSinceDate:startDate]];

return kmlData;
}

This call blocks until the request fails (returning nil and an error is produced) or the data finishes downloading. The several if clauses check if the response data contain any misleading or unwanted data which my come from downloading from the wrong website.

For using the simpleKML Library you need to download the framework from this github project.
https://github.com/incanus/Simple-KML/

Taggings: