【问题标题】:How to download image?如何下载图像?
【发布时间】:2016-11-19 13:53:49
【问题描述】:

使用此代码下载图像。但是图像没有出现在显示器上。

  NSURL *url = [NSURL URLWithString:
 @"http://upload.wikimedia.org/wikipedia/commons/7/7f/Williams_River-27527.jpg"];

NSURLSessionDownloadTask *downloadPhotoTask = [[NSURLSession sharedSession]
 downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
  _downloadedImage = [UIImage imageWithData:
    [NSData dataWithContentsOfURL:location]];
}];

// 4    
[downloadPhotoTask resume];

_downloadedImage = [UIImage imageNamed:@"Williams_River-27527.jpg"];
    [_book3 setBackgroundImage: _downloadedImage forState:UIControlStateNormal];
    [_scroller addSubview:_book3];

UPD

我在我的 xcode 项目中更新了我的代码,但它也不起作用……为什么它的代码在我的 Xcode 项目中也不起作用?

#import "ViewController.h"

@interface ViewController () <NSURLSessionDelegate, NSURLSessionDownloadDelegate>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:nil];
    NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithURL:[NSURL URLWithString:@"http://cdn.tutsplus.com/mobile/uploads/2013/12/sample.jpg"]];
    [downloadTask resume];

}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
    NSData *data = [NSData dataWithContentsOfURL:location];

    dispatch_async(dispatch_get_main_queue(), ^{
        [self.progressView setHidden:YES];
        [self.imageView setImage:[UIImage imageWithData:data]];
    });
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes {

}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
    float progress = (double)totalBytesWritten / (double)totalBytesExpectedToWrite;

    dispatch_async(dispatch_get_main_queue(), ^{
        [self.progressView setProgress:progress];
    });
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

为什么它的代码在我的 Xcode 项目中也不起作用?

【问题讨论】:

  • 首先,您尝试加载刚刚下载的图像UIImage(在内存中),就好像它在您的捆绑包中一样。其次,您正在尝试在异步完成下载之前加载图像...

标签: ios objective-c nsurl


【解决方案1】:

如果您希望它像代码一样工作(不确定是否会),那么您需要运行此过程中的步骤:

//1     
NSURL *url = [NSURL URLWithString:
  @"http://upload.wikimedia.org/wikipedia/commons/7/7f/Williams_River-27527.jpg"];

// 2    
NSURLSessionDownloadTask *downloadPhotoTask = [[NSURLSession sharedSession]
 downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
    // 3 
    _downloadedImage = [UIImage imageWithData:
    [NSData dataWithContentsOfURL:location]];

    //5
    dispatch_async(dispatch_get_main_queue(), ^{
        [_book3 setBackgroundImage: _downloadedImage forState:UIControlStateNormal];
        [_scroller addSubview:_book3];
    });
}];

// 4    
[downloadPhotoTask resume];

【讨论】:

    【解决方案2】:

    这是 Swift 的答案

        let url = URL.init(string: "https:yourUrl.com") as! URL
    
        URLSession.shared.dataTask(with: url) { (data, response, error) in
            if let error = error {
                print("Error needs to be handled")
                return
            }
    
            let image = UIImage.init(data: data!)
            DispatchQueue.main.async {
                self.yourImageView.image = image
            }
        }.resume()
    

    【讨论】:

      【解决方案3】:

      您通过从包中加载图像来创建图像的第一个实例:_downloadedImage = [UIImage imageNamed:@"Williams_River-27527.jpg"];(希望有一个)

      从您的网址下载图像后,您将创建一个包含下载内容的图像的第二个实例。但是您的按钮仍然链接到 first 实例(强参考)。按钮根本不知道新图像。

      所以如果你想改变显示的图像你必须在分配给_downloadedImage:[_book3 setBackgroundImage: _downloadedImage forState:UIControlStateNormal];之后直接重新设置它

      之后可能需要刷新用户界面。

      【讨论】:

        【解决方案4】:

        Xamarin.iOS 的简单而纯粹的答案:

        var url = new NSUrl("https:yourUrl.com");
        
        var task = await NSUrlSession.SharedSession.CreateDataTaskAsync(url);
        var image = UIImage.LoadFromData(task.Data);
        
        yourImageView.Image = image;
        

        【讨论】:

          猜你喜欢
          • 2019-12-24
          • 2017-05-20
          • 2016-09-06
          • 2012-08-16
          • 2014-09-07
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多