我想知道是否有人能帮我。如果我将图像URL放入我的textfield中,我将尝试使用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];
}我不知道以后该去哪儿。
发布于 2014-11-10 20:45:10
有两种选择:
[NSURLSession sharedSession],并将downloadTaskWithRequest与completionHandler一起呈现。例如:
类型(Self) __weak weakSelf = self;//没有下载保留此视图控制器NSURLSessionTask* downloadTask =[会话下载the :请求完成处理程序:^(NSURL *location,NSURLResponse *response,NSError * error ) { // if错误,处理它并退出如果(错误){ NSLog(@"downloadTaskWithRequest故障:%@",错误);返回;} //如果确定,移动文件NSFileManager *fileManager = NSFileManager defaultManager;NSURL *documentsURL = fileManager URLsForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask;NSURL *fileURL = documentsURL URLByAppendingPathComponent:filename;NSError *moveError;if () { NSLog(@"moveItemAtURL fileURL:%@",moveError);返回;} // create图像视图(在主队列上) UIImage *image = [UIImage imageWithContentsOfFile:fileURL路径];如果(图像){ dispatch_async(dispatch_get_main_queue(),^{ weakSelf.imageView.image =weakSelf.imageView.image;});}];downloadTask恢复;
显然,对下载的文件做任何你想做的事情(如果你想把它放在其他地方),但这可能是基本的模式。NSURLSession创建session:delegate:queue:并指定您的delegate,在其中您将遵循NSURLSessionDownloadDelegate并处理下载的完成。前者更容易,但后者更丰富(例如,如果您需要特殊的委托方法,例如身份验证、检测重定向等,或者如果您想使用后台会话,则非常有用)。
顺便说一句,不要忘了使用[downloadTask resume],否则下载就不会开始了。
https://stackoverflow.com/questions/26851121
复制相似问题