开发者

Create a UIImage with a URL in iOS

开发者 https://www.devze.com 2023-04-12 02:44 出处:网络
To create an UiImage with a image file, I use the code as below: UIImage *aImage = [[UIImage imageNamed:@\"demo.jpg\"]autorelease];

To create an UiImage with a image file, I use the code as below:

UIImage *aImage = [[UIImage imageNamed:@"demo.jpg"]autorelease];

If I want to cr开发者_运维百科eate an UiImage with the URL http://example.com/demo.jpg, how to do that?

Thanks

UPDATE

Create a UIImage with a URL in iOS


This is a three step process. First you will create an NSURL object to hold the URL we are attempting to access. We will supply this URL to the NSData class method, +dataWithContentsOfURL: to obtain the image over the network as raw data, then use the +imageWithData: class method on UIImage to convert the data into an image.

NSURL *imageURL = [NSURL URLWithString:@"http://example.com/demo.jpg"];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:imageData];

Please note that +dataWithContentsOfURL: executes a synchronous network request. If you run this on the main thread, it will block the UI until the image data is received from the network. Best practice is to run any network code on a background thread. If you're targeting OS 4.0+ you could do something like this...

NSURL *imageURL = [NSURL URLWithString:@"http://example.com/demo.jpg"];

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
    NSData *imageData = [NSData dataWithContentsOfURL:imageURL];

    dispatch_async(dispatch_get_main_queue(), ^{
        // Update the UI
        self.imageView.image = [UIImage imageWithData:imageData];
    });
});


Here's what the same code might look like in Swift:

let image_url = NSURL("http://i.imgur.com/3yY2qdu.jpg")

let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority, 0)) {
    // do some task
    let image_data = NSData(contentsOfURL: image_url!)

    dispatch_async(dispatch_get_main_queue()) {
        // update some UI
        let image = UIImage(data: image_data!)
        self.imageView.image = image
    }
}


For anyone looking to load image from the web the following library may be helpful:

https://github.com/rs/SDWebImage

It's a UIImageView category which handles async loading and image caching from url.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号