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