我想知道是否有人可以帮助我.我正在尝试使用NSURLSessionDownloadTask在我的UI ImageView中显示图片,如果我将图像URL放入我的文本字段中. -(IBAction)go:(id)sender { NSString* str=_urlTxt.text; NSURL* URL =
-(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],使用completionHandler下载downloadTaskWithRequest.例如:
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];
显然,使用下载的文件做任何你想做的事情(如果你愿意,把它放在其他地方),但这可能是基本模式
>使用session:delegate:queue:创建NSURLSession并指定您的委托,您将在其中符合NSURLSessionDownloadDelegate并处理完成下载.
前者更容易,但后者更丰富(例如,如果您需要特殊的委托方法,例如身份验证,检测重定向等,或者如果您想使用后台会话,则非常有用).
顺便说一句,不要忘记[downloadTask resume],否则下载将无法启动.