title: Slow downloading of photos with NSURLSession
body: <p>I am using the NSURLSession API to ask my Java servlet for some photo uploaded on my server. I then display the photo on the device in some UIImageView. The problem is it might take up to ten seconds to finally display a photo, which is about 100 ko. Needless to say this is unacceptable. Here is the code I use:</p>
  
  <pre><code>@interface ViewPhotoViewController () &lt;UIAlertViewDelegate&gt;
  
  @property (weak, nonatomic) IBOutlet UIImageView *imageView;
  @property (nonatomic) NSURLSession *session;
  
  @end
  
  - (void)viewDidLoad {
  [super viewDidLoad];
  NSURLSessionConfiguration *config =
  [NSURLSessionConfiguration defaultSessionConfiguration];
  self.session = [NSURLSession sessionWithConfiguration:config
                                               delegate:nil
                                          delegateQueue:nil];
  NSString *requestedURL=[NSString stringWithFormat:@"http://myurl.com/myservlet?filename=%@", self.filename];
  NSURL *url = [NSURL URLWithString:requestedURL];
  
  NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
  [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
  [request setHTTPShouldHandleCookies:NO];
  [request setTimeoutInterval:30];
  [request setHTTPMethod:@"GET"];
  [request setURL:url];
  
  //Maintenant on la lance
  
  NSURLSessionDownloadTask *downloadTask = [self.session downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
      NSData *downloadedData = [NSData dataWithContentsOfURL:location
                                                     options:kNilOptions
                                                       error:nil];
      NSLog(@"Done");
      NSLog(@"Size: %lu", (unsigned long)downloadedData.length);
      UIImage *image = [UIImage imageWithData:downloadedData];
  
      if (image) self.imageView.image = image;
  }];
  [downloadTask resume];
  }
  </code></pre>
  
  <p>The weird thing is that I get the "Done" and "Size" logs very quickly, but the photo still appears after a lot of seconds. What is wrong with my code?</p>