[iOS] Loading Image from URL iOS

Posted in :

NSURL *url = [NSURL URLWithString:path];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [[UIImage alloc] initWithData:data];

I will just adapt Jim Dovey answer from here Getting Image from URL Objective C :

Synchronous version

NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: @"http://myurl/mypic.jpg"]];
UIImageView *imView = [[UIImageView alloc] initWithImage:[UIImage imageWithData: imageData]];

Asynchronous version

dispatch_async(dispatch_get_global_queue(0,0), ^{
    NSData * data = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: @"http://myurl/mypic.jpg"]];
    if ( data == nil )
        return;
    dispatch_async(dispatch_get_main_queue(), ^{
        UIImageView *imView = [[UIImageView alloc] initWithImage:[UIImage imageWithData: data]];
    });
});
 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *