Download image from URL.

I'll throw on a few examples using asynchronous requests.



1. blocks in NSURLConnection


- (void)NSURLConnectionExample
{
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com/images/srpr/logo3w.png"] cachePolicy:NSURLCacheStorageNotAllowed timeoutInterval:10.0];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *err){
        if (!err && data) {
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *documents = [paths objectAtIndex:0];
            NSString *finalPath = [documents stringByAppendingPathComponent:@"myImageName.png"];
            [data writeToFile:finalPath atomically:YES];
        }
    }];
}

2. Grand Central Dispatch.


Method 1:

[self downloadImageForURL:imgUrlString successBlock:^(UIImage *imagee) {
    //Your Image
}];


- (void)downloadImageForURL:(NSString *)url successBlock:(void (^)(UIImage *image))downloadedImage {
    
    NSURL *imageURL = [NSURL URLWithString:url];
    
    dispatch_queue_t aQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT0);
    dispatch_async(aQueue, ^{
        NSData *data = [NSData dataWithContentsOfURL:imageURL];
        dispatch_async(dispatch_get_main_queue(), ^{
            UIImage *image = [UIImage imageWithData:data];
            downloadedImage(image);
        });
    });
}

Method 2 : 
- (void)GrandCentralDispatchExample
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documents = [paths objectAtIndex:0];
    NSString *finalPath = [documents stringByAppendingPathComponent:@"myImageName.png"];

    dispatch_queue_t imageQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,  0ul);

    dispatch_async(imageQueue, ^{
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com/images/srpr/logo3w.png"]];
                             dispatch_async(dispatch_get_main_queue(), ^{
                                 [data writeToFile:finalPath atomically:YES];
                             });

    });
}

3. GCD


[self.photo processImageDataWithBlock:^(NSData *imageData) {
        UIImage *image = [UIImage imageWithData:imageData];
}];


- (void)processImageDataWithBlock:(void (^)(NSData *imageData))processImage
{
NSString *url = self.imageURL;
dispatch_queue_t callerQueue = dispatch_get_current_queue();
dispatch_queue_t downloadQueue = dispatch_queue_create("Photo Downloader", NULL);
dispatch_async(downloadQueue, ^{
    NSData *imageData = *insert code that fetches photo from server*;
    dispatch_async(callerQueue, ^{
        processImage(imageData);
    });
});
dispatch_release(downloadQueue);
}

Now save your image where ever  you want.(Document directory , TempDirectory)


-(void) saveImage:(UIImage *)image withFileName:(NSString *)imageName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath {
    if ([[extension lowercaseString] isEqualToString:@"png"]) {
        [UIImagePNGRepresentation(image) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", imageName, @"png"]] options:NSAtomicWrite error:nil];
    } else if ([[extension lowercaseString] isEqualToString:@"jpg"] || [[extension lowercaseString] isEqualToString:@"jpeg"]) {
        [UIImageJPEGRepresentation(image, 1.0) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", imageName, @"jpg"]] options:NSAtomicWrite error:nil];
    } else {
        ALog(@"Image Save Failed\nExtension: (%@) is not recognized, use (PNG/JPG)", extension);
    }
}






BLOCK

Way 0 :

[self downloadImageForURL:picUrl successBlock:^(UIImage *imagee) {
    //Your Image
}];


- (void)downloadImageForURL:(NSString *)url successBlock:(void (^)(UIImage *image))downloadedImage {
    
    NSURL *imageURL = [NSURL URLWithString:url];
    
    dispatch_queue_t aQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(aQueue, ^{
        NSData *data = [NSData dataWithContentsOfURL:imageURL];
        dispatch_async(dispatch_get_main_queue(), ^{
            UIImage *image = [UIImage imageWithData:data];
            downloadedImage(image);
        });
    });
}

way 1 ->

UIImage *(^getImage)(NSString *) = ^(NSString *url)
        {
            UIImage *image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url]]];

            return image;
        };


imageView.image=getImage(imageURL);


way 2 ->

[self downloadImage_imageURL:make :^(UIImage *image){
        cell.imageView.image=image;
    }]; 
 
 
 -(void) downloadImage_imageURL:(NSString*)url :(myCompletion) compblock{

    UIImage *image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:url]]];

    compblock(image);
}





Comments

Popular posts from this blog

How to Make REST api call in Objective-C.

Launch iPhone simulator without Xcode.

Hacker Rank problem solution