ios 如何使用链接中的图像创建 UIImageView?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3562602/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 17:36:36  来源:igfitidea点击:

How to create UIImageView with image from a link?

iosiphonemacosuiimageviewuiimage

提问by asedra_le

How to create UIImageView with image from a link like this http://img.abc.com/noPhoto4530.gif?

如何从这样的链接创建带有图像的 UIImageView http://img.abc.com/noPhoto4530.gif

回答by nszombie

NSURL *url = [NSURL URLWithString:@"http://img.abc.com/noPhoto4530.gif"];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];

回答by neowinston

If you want to download the picture in the background, and then set it on the main thread, you can do it like this:

如果你想在后台下载图片,然后在主线程中设置,你可以这样做:

- (void)downloadPicture {

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

                NSURL *url = [NSURL URLWithString:@"http://img.abc.com/noPhoto4530.gif"];

                UIImage *image = [self getPicture:url];

                dispatch_async(dispatch_get_main_queue(), ^{

                    [self setPicture:image];

                });
            });
}

 - (UIImage *)getPicture:(NSURL *)pictureURL {

        NSData *data = [NSData dataWithContentsOfURL:pictureURL];
        UIImage *image = [UIImage imageWithData:data];

        return image;    
}

 - (void)setPicture:(UIImage *)image {

        UIImageView * imageView = [[UIImageView alloc] initWithFrame:
                               CGRectMake(kPictureX, kPictureY, image.size.height, image.size.width)];

        [imageView setImage:image];

        [self.view addSubview: imageView];

}

回答by John Erck

Here's a code snippet for those looking to use iOS 7's new suite of NSURLSession classes:

对于那些希望使用 iOS 7 的新 NSURLSession 类套件的人来说,这是一个代码片段:

// Set NSURLSessionConfig to be a default session
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];

// Create session using config
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];

// Create URL
NSURL *url = [NSURL URLWithString:@"https://www.google.com/images/srpr/logo11w.png"];

// Create URL request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"GET";

// Create data task
NSURLSessionDataTask *getDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

    // Okay, now we have the image data (on a background thread)
    UIImage *image = [UIImage imageWithData:data];

    // We want to update our UI so we switch to the main thread
    dispatch_async(dispatch_get_main_queue(), ^{

        // Create image view using fetched image (or update an existing one)
        UIImageView *imageView = [[UIImageView alloc] initWithImage:image];

        // Do whatever other UI updates are needed here on the main thread...
    });
}];

// Execute request
[getDataTask resume];

回答by No one in particular

Download image to a local path on your device then get a UIImage from imageWithContentsOfFileand use this to set the image in the UIImageView. Remember to cleanup your image file sometime.

将图像下载到设备上的本地路径,然后从中获取 UIImageimageWithContentsOfFile并使用它在UIImageView. 记得在某个时候清理你的图像文件。

回答by neowinston

After downloading the image you need also to place it as a subview from a view, like so:

下载图像后,您还需要将其作为视图的子视图放置,如下所示:

NSURL *url = [NSURL URLWithString:@"http://img.abc.com/noPhoto4530.gif"];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];

UIImageView * myImageView = [[UIImageView alloc] initWithImage:image];
[someOtherView addSubview:myImageView];
[myImageView release];

回答by imaginaryboy

You can either do as described here, or you can use NSURLConnection to download the image data and create the UIImage to set to you UIImageView. I personally prefer using NSURLConnection to download the image asynchronously.

您可以按照此处所述进行操作,也可以使用 NSURLConnection 下载图像数据并创建 UIImage 以设置为您的 UIImageView。我个人更喜欢使用 NSURLConnection 异步下载图像。

回答by user3182143

Same answer can have here

相同的答案可以在这里

NSURL *urlLink = [NSURL URLWithString:@"http://img.abc.com/noPhoto4530.gif"];
NSData *dataURL = [NSData dataWithContentsOfURL:urlLink];
UIImage *imageData = [UIImage imageWithData:dataURL];
UIImageView *imageView = [[UIImageView alloc] initWithImage:imageData];

回答by Shijing Lv

you can try modern gcd style (xcode 8.0+):

您可以尝试现代 gcd 风格(xcode 8.0+):

let queue = DispatchQueue(label: "com.mydomain.queue3")
queue.async {
    let imageURL: URL = URL(string: "https://www.brightedge.com/blog/wp-content/uploads/2014/08/Google-Secure-Search_SEL.jpg")!
    guard let imageData = try? Data(contentsOf: imageURL) else {
        return
    }
    DispatchQueue.main.async {
        self.imageView.image = UIImage(data: imageData)
    }
}

you can also replace the first DispatchQueuewith URLSession.dataTask

你也可以DispatchQueueURLSession.dataTask

let imageURL: URL = URL(string: "https://www.brightedge.com/blog/wp-content/uploads/2014/08/Google-Secure-Search_SEL.jpg")!

(URLSession(configuration: URLSessionConfiguration.default)).dataTask(with: imageURL, completionHandler: { (imageData, response, error) in

    if let data = imageData {
        print("Did download image data")

        DispatchQueue.main.async {
            self.imageView.image = UIImage(data: data)
        }
    }
}).resume()