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];
}
奇怪的是,我得到的“完成”和“大小”日志很快,但照片很多秒钟后仍出现。我的代码有什么问题?
我并没有意识到这一点,谢谢。 – Gannicus