0

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:

@interface ViewPhotoViewController () <UIAlertViewDelegate>

@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];
}

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?

Gannicus
  • 399
  • 1
  • 3
  • 18

1 Answers1

1

Thats because you completion block is not called on the main thread, which means that your call to self.imageView.image = image; is not made on the main thread. You're actually lucky that it works, all UIKit related work should be done on the main thread.

So replace if (image) self.imageView.image = image; by this :

if (image) {
    dispatch_async(dispatch_get_main_queue(), ^{
        self.imageView.image = image;
    });
}
deadbeef
  • 5,409
  • 2
  • 17
  • 47