gpt4 book ai didi

ios - 使用 NSURLSessionDownloadTask 显示图像

转载 作者:可可西里 更新时间:2023-11-01 17:06:31 26 4
gpt4 key购买 nike

我想知道是否有人可以帮助我。如果我将图像 URL 放入我的文本字段,我将尝试使用 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];
}

我不确定在这之后该去哪里。

最佳答案

两种选择:

  1. 使用 [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];

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

  2. 使用 session:delegate:queue: 创建 NSURLSession 并指定您的 delegate,您将在其中符合 NSURLSessionDownloadDelegate 并在那里处理下载的完成。

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

对了,不要忘记[downloadTask resume],否则下载不会开始。

关于ios - 使用 NSURLSessionDownloadTask 显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26851121/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com