How to create UIImageView with image from a link?

2020-05-19 05:52发布

问题:

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

回答1:

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


回答2:

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

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


回答3:

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

}


回答4:

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


回答5:

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



回答6:

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.



回答7:

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


回答8:

you can try modern gcd style (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 DispatchQueue with URLSession.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()