使用NSURLSessionDownloadTask显示图像

Cor*_*ory 3 objective-c uiimageview ios nsurlsession nsurlsessiondownloadtask

我想知道是否有人可以帮助我.我正在尝试使用NSURLSessionDownloadTask在我的UIImageView中显示图片,如果我将图像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];
}
Run Code Online (Sandbox Code Playgroud)

我不知道在此后去哪里.

Rob*_*Rob 7

两种选择:

  1. 使用[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];
    
    Run Code Online (Sandbox Code Playgroud)

    显然,使用下载的文件做任何你想做的事情(如果你愿意,把它放在其他地方),但这可能是基本模式

  2. 创建NSURLSession使用session:delegate:queue:并指定您delegate将遵守NSURLSessionDownloadDelegate并处理完成下载的内容.

前者更容易,但后者更丰富(例如,如果您需要特殊的委托方法,例如身份验证,检测重定向等,或者如果您想使用后台会话,则非常有用).

顺便说一句,不要忘记[downloadTask resume],否则下载将无法启动.