title: How to asynchronously load an image in an UIImageView?
body: <p>I have an UIView with an UIImageView subview. I need to load an image in the UIImageView without blocking the UI. The blocking call seems to be: <code>UIImage imageNamed:</code>. Here is what I thought solved this problem:</p>
  
  <pre><code>-(void)updateImageViewContent {
      dispatch_async(
          dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
          UIImage * img = [UIImage imageNamed:@"background.jpg"];
          dispatch_sync(dispatch_get_main_queue(), ^{
              [[self imageView] setImage:img];
          });
      });
  }
  </code></pre>
  
  <p>The image is small (150x100).</p>
  
  <p>However the UI is still blocked when loading the image. What am I missing ?</p>
  
  <p>Here is a small code sample that exhibits this behaviour:</p>
  
  <p>Create a new class based on UIImageView, set its user interaction to YES, add two instances in a UIView, and implement its touchesBegan method like this:</p>
  
  <pre><code>-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
      if (self.tag == 1) {
          self.backgroundColor= [UIColor redColor];
      }
  
      else {
      dispatch_async(dispatch_get_main_queue(), ^{
      [self setImage:[UIImage imageNamed:@"woodenTile.jpg"]];
    });
      [UIView animateWithDuration:0.25 animations:
          ^(){[self setFrame:CGRectInset(self.frame, 50, 50)];}];
      }
  }
  </code></pre>
  
  <p>Assign the tag 1 to one of these imageViews. </p>
  
  <p>What happens exactly when you tap the two views almost simultaneously, starting with the view that loads an image? Does the UI get blocked because it's waiting for <code>[self setImage:[UIImage imageNamed:@"woodenTile.jpg"]];</code> to return ? If so, how may I do this asynchronously ?</p>
  
  <p>Here is a  <a href="https://github.com/alecail/qcv" rel="noreferrer">project on github</a> with ipmcc code </p>
  
  <p>Use a long press then drag to draw a rectangle around the black squares. As I understand his answer, in theory the white selection rectangle should not be blocked the first time the image is loaded, but it actually is.</p>
  
  <p>Two  images are included in the project (one small: woodenTile.jpg and one larger: bois.jpg). The result is the same with both.</p>
  
  <h2>Image format</h2>
  
  <p>I don't really understand how this is related to the problem I still have with the UI being blocked while the image is loaded for the first time, but PNG images decode without blocking the UI, while JPG images do block the UI.</p>
  
  <h2> Chronology of the events </h2>
  
  <p><img src="https://i.stack.imgur.com/QFfCQ.jpg" alt="step 0">
  <img src="https://i.stack.imgur.com/7e4tI.jpg" alt="step 1"></p>
  
  <p>The blocking of the UI begins here..</p>
  
  <p><img src="https://i.stack.imgur.com/kBamp.jpg" alt="step 2"></p>
  
  <p>.. and ends here.</p>
  
  <p><img src="https://i.stack.imgur.com/AbQdo.jpg" alt="step 3"></p>
  
  <h2> AFNetworking solution </h2>
  
  <pre><code>    NSURL * url =  [ [NSBundle mainBundle]URLForResource:@"bois" withExtension:@"jpg"];
      NSURLRequest * request = [NSURLRequest requestWithURL:url];
      [self.imageView setImageWithURLRequest:request
                            placeholderImage:[UIImage imageNamed:@"placeholder.png"]
                                     success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
                                         NSLog(@"success: %@", NSStringFromCGSize([image size]));
                                     } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
                                         NSLog(@"failure: %@", response);
                                     }];
  
  // this code works. Used to test that url is valid. But it's blocking the UI as expected.
  if (false)       
  if (url) {
          [self.imageView setImage: [UIImage imageWithData:[NSData dataWithContentsOfURL:url]]]; }
  </code></pre>
  
  <p>Most of the time, it logs: <code>success: {512, 512}</code></p>
  
  <p>It also occasionnaly logs: <code>success: {0, 0}</code></p>
  
  <p>And sometimes: <code>failure: &lt;NSURLResponse: 0x146c0000&gt; { URL: file:///var/mobile/Appl...</code></p>
  
  <p>But the image is never changed.</p>