3

I was wondering if someone could help me out. I'm trying to use NSURLSessionDownloadTask to display a picture in my UIImageView if I put the image URL into my textfield.

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

I am not sure where to go after this.

4

1 回答 1

7

两种选择:

  1. 使用[NSURLSession sharedSession],downloadTaskWithRequestcompletionHandler. 例如:

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

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

  2. 创建NSURLSessionusingsession:delegate:queue:并指定您delegate的 ,您将在其中遵守NSURLSessionDownloadDelegate并处理那里的下载完成。

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

顺便说一句,不要忘记[downloadTask resume],否则下载将无法开始。

于 2014-11-10T20:45:10.477 回答