Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to asynchronously download files in a specific order in iOS?
    text
    copied!<p>My iPhone app makes a asynchronous request with <code>NSURLRequest</code> to my site.</p> <p>The response is JSON with 10 URLs to images. When I receive the asynchronous response I want to download the 10 files using a loop, creating an <code>NSMutableArray</code> of <code>UIImage</code> objects.</p> <p>I tried to do this with the method <code>NSData dataWithContentsOfURL</code>, and it works but isn't asynchronous, so the user interface is blocked. </p> <p>If I try to use the <code>NSURL</code> asynchronous method inside the response of this asynchronous method, when I receive the 10 responses with the images, I can't know if the images have been downloaded in order, and in my application the order is important.</p> <p>What is a solution for downloading files in order, without blocking the UI?</p> <p>My code:</p> <pre><code>// Create the request. NSString *advertURL = [NSString stringWithFormat: @"http://www.myURL"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:advertURL] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; // Create url connection and fire request imagesConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; </code></pre> <p>When I receive response:</p> <pre><code>//decode json with the urls NSArray* json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&amp;error]; //star the loop to downloading the ten images for (int i=0; i&lt;10; i++) { //find image[i] url from json NSString *fullImage_URL = json[i][@"url"]; //download image synchronously (this blocks the UI!!) NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fullImage_URL]]; //insert image in the array arrayImages[i] = [UIImage imageWithData:data]; } </code></pre> <p>Then, when I'm sure the array has 10 images and they're in order, I can start to show images on the screen.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload