Create UIImage with url in iOS

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

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

If I want to create a UiImage with the URL http://example.com/demo.jpg , how do I do this?

thank

UPDATE

enter image description here

+46
ios objective-c uikit uiimage
Oct 08 2018-11-11T00:
source share
3 answers

This is a three-step process. First, you create an NSURL object to store the URL that we are trying to access. We will pass this URL to the NSData class method, +dataWithContentsOfURL: to get the image over the network as raw data, then use the +imageWithData: class method on UIImage to convert the data to an image.

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

Note that +dataWithContentsOfURL: performs a synchronous network request. If you run this in the main thread, it will block the user interface until the image data is received from the network. Best practice is to run any network code in a background thread. If you focus on OS 4.0+, you can 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]; }); }); 
+146
Oct 08 2018-11-11T00:
source share

Here is what the 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 } } 
+6
Oct 24 '14 at 1:35
source share

For those who want to download an image from the Internet, the following library may be useful:

https://github.com/rs/SDWebImage

This is the UIImageView category that handles asynchronously loading and caching images from URLs.

0
Jun 02 '16 at 19:08
source share



All Articles