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(), ^{
Mark Adams Oct 08 2018-11-11T00: 00Z
source share