2015-08-20 48 views
0

我正在使用NSURLSession API向我的Java servlet请求在我的服务器上上传的某些照片。然后,我在某些UIImageView中的设备上显示照片。问题是可能需要十秒钟才能最终显示约100张照片。不用说这是不可接受的。下面是我的代码使用方法:使用NSURLSession缓慢下载照片

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

奇怪的是,我得到的“完成”和“大小”日志很快,但照片很多秒钟后仍出现。我的代码有什么问题?

回答

1

那是因为你的完成块没有在主线程中调用,这意味着你的调用self.imageView.image = image;不是在主线程上进行的。你真的很幸运,它的所有UIKit相关工作都应该在主线程中完成。

那么这个替代if (image) self.imageView.image = image;

if (image) { 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     self.imageView.image = image; 
    }); 
} 
+0

我并没有意识到这一点,谢谢。 – Gannicus