使用NSURLSessionDownloadTask显示图片

3

我想知道是否有人能够帮助我。我试图使用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];
}

我不确定接下来该去哪里。

这句话与IT技术无关,请提供更多需要翻译的内容。
1个回答

7

有两个选项:

  1. Use [NSURLSession sharedSession], with rendition of downloadTaskWithRequest with the completionHandler. For example:

    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];
    

    Clearly, do whatever you want with the downloaded file (put it somewhere else if you want), but this might be the basic pattern

  2. Create NSURLSession using session:delegate:queue: and specify your delegate, in which you'll conform to NSURLSessionDownloadDelegate and handle the completion of the download there.

前者更容易,但后者更丰富(例如,如果您需要特殊的委托方法,例如身份验证、检测重定向等,则非常有用,或者如果您想要使用后台会话)。
顺便说一下,不要忘记执行 [downloadTask resume],否则下载将不会开始。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接