user3600801
user3600801

Reputation:

Loading images dynamically from web to ui

I have to download an image and store it in a NSMutableArray. Then I have to access it later and display

I'm using the following code to download the images to documents folder,

NSString *documentDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *filePath = [documentDir stringByAppendingPathComponent:@"GoogleLogo.png"];

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.google.com/images/srpr/logo11w.png"]];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
        if (error) {
            NSLog(@"Download Error:%@",error.description);
        }
        if (data) {
            [data writeToFile:filePath atomically:YES];
            NSLog(@"File is saved to %@",filePath);
            NSString *fileName = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"tmp/%@",filePath]];
            // NSLog(@"sddsd %@",fileName);
        } 
    }];

How to add all downloaded images to a NSMutableArray and access it later?

Upvotes: 0

Views: 45

Answers (2)

Shravan
Shravan

Reputation: 438

Try using SDWebImage Class to set image to the imageview dynamically from web

Import following file to your header file.

import "UIImageView+WebCache.h"

after importing file try following code.

[self.imgLogo sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",[self.dictTemp valueForKey:@"camp_image"]]] placeholderImage:[UIImage imageNamed:@"placeholder.jpg"]];

It is generally used to cache the images so it will be accessible later

Upvotes: 1

Rajesh
Rajesh

Reputation: 10434

THis is the way you can load images

NSMutableArray *array = [NSMutableArray array];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.google.com/images/srpr/logo11w.png"]];
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
            if (error) {
                NSLog(@"Download Error:%@",error.description);
            } else if (data) {
[array addObject:[UIImage imageWithData:data]];
            } 
        }];

If you want to load asynchronously with cache this library helps you.

AsyncImageView

Upvotes: 0

Related Questions