我想知道是否有人可以帮助我。如果我将图像URL放入文本字段,则尝试使用NSURLSessionDownloadTask在UIImageView中显示图片。
-(IBAction)go:(id)sender {
NSString* str=_urlTxt.text;
NSURL* URL = [NSURL URLWithString:str];
NSURLRequest* req = [NSURLRequest requestWithURL:url];
NSURLSession* session = [NSURLSession sharedSession];
NSURLSessionDownloadTask* downloadTask = [session downloadTaskWithRequest:request];
}
我不确定此后该去哪里。
两种选择:
使用[NSURLSession sharedSession]
,用的再现downloadTaskWithRequest
用completionHandler
。例如:
typeof(self) __weak weakSelf = self; // don't have the download retain this view controller
NSURLSessionTask* downloadTask = [session downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
// if error, handle it and quit
if (error) {
NSLog(@"downloadTaskWithRequest failed: %@", error);
return;
}
// if ok, move file
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *documentsURL = [fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask][0];
NSURL *fileURL = [documentsURL URLByAppendingPathComponent:filename];
NSError *moveError;
if (![fileManager moveItemAtURL:location toURL:fileURL error:&moveError]) {
NSLog(@"moveItemAtURL failed: %@", moveError);
return;
}
// create image and show it im image view (on main queue)
UIImage *image = [UIImage imageWithContentsOfFile:[fileURL path]];
if (image) {
dispatch_async(dispatch_get_main_queue(), ^{
weakSelf.imageView.image = image;
});
}
}];
[downloadTask resume];
显然,对下载的文件执行任何操作(如果需要,可以将其放置在其他位置),但这可能是基本模式
NSURLSession
使用创建session:delegate:queue:
并指定您的delegate
,在其中您将遵循NSURLSessionDownloadDelegate
并在那里完成下载。
前者更容易,但后者则更丰富(例如,如果您需要特殊的委托方法,例如身份验证,检测重定向等,或者如果您想使用后台会话,则很有用)。
顺便说一句,别忘了登录[downloadTask resume]
,否则下载将不会开始。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句