-2

I want to retrieve a folder containing 10 images from server, then store that folder in my document directory. I did some code, but when I run it, I am getting the image urls, not the images themselves. Can anyone help me out?

My code:

-(void)viewWillAppear:(BOOL)animated
{

NSMutableData *receivingData = [[NSMutableData alloc] init];
NSURL *url = [NSURL URLWithString:@"http://Someurl.filesCount.php"];
NSURLRequest *req = [NSURLRequest requestWithURL:url];


   NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:YES];

}

-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{

[receivingData appendData:data];
}
-(void) connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *error = nil;

{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
printf("\n the path is :%s",[path UTF8String]);


NSString *zipPath = [path stringByAppendingPathComponent:@"filesCount.php"];

[receivingData writeToFile:zipPath options:0 error:&error];



        NSString *documentsDirectoryPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"filesCount"];
        NSLog(@"the path %@",documentsDirectoryPath);



}
vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
  • You are downloading the image correctly and to save the image check this link may it help you little http://stackoverflow.com/questions/6821517/save-an-image-to-application-documents-folder-from-uiview-on-ios – Exploring Feb 19 '13 at 06:32

4 Answers4

1

I made this function in my previous project. You need to pass your imageView and serverUrl, then its automatically show image in your imageView and save image to temp directory, when you want again to fetch same image, then next time it take image from disk.

+(void)downloadingServerImageFromUrl:(UIImageView*)imgView AndUrl:(NSString*)strUrl{

NSFileManager *fileManager =[NSFileManager defaultManager];

NSString* theFileName = [NSString stringWithFormat:@"%@.png",[[strUrl lastPathComponent] stringByDeletingPathExtension]];
NSString *fileName = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"tmp/%@",theFileName]];


imgView.backgroundColor = [UIColor darkGrayColor];
UIActivityIndicatorView *actView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
[imgView addSubview:actView];
[actView startAnimating];
CGSize boundsSize = imgView.bounds.size;
CGRect frameToCenter = actView.frame;
// center horizontally
if (frameToCenter.size.width < boundsSize.width)
    frameToCenter.origin.x = (boundsSize.width - frameToCenter.size.width) / 2;
else
    frameToCenter.origin.x = 0;

// center vertically
if (frameToCenter.size.height < boundsSize.height)
    frameToCenter.origin.y = (boundsSize.height - frameToCenter.size.height) / 2;
else
    frameToCenter.origin.y = 0;

actView.frame = frameToCenter;


dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{

    NSData *dataFromFile = nil;
    NSData *dataFromUrl = nil;

    dataFromFile = [fileManager contentsAtPath:fileName];
    if(dataFromFile==nil){
        dataFromUrl=[[[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:strUrl]] autorelease];
    }

    dispatch_sync(dispatch_get_main_queue(), ^{

        if(dataFromFile!=nil){
            imgView.image = [UIImage imageWithData:dataFromFile];
        }else if(dataFromUrl!=nil){
            imgView.image = [UIImage imageWithData:dataFromUrl];
            // NSString *fileName = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"tmp/%@",theFileName]];

            BOOL filecreationSuccess = [fileManager createFileAtPath:fileName contents:dataFromUrl attributes:nil];
            if(filecreationSuccess == NO){
                NSLog(@"Failed to create the html file");
            }

        }else{
            imgView.image = [UIImage imageNamed:@"NO_Image.png"];
            imgView.tag = 105;
        }
        [actView removeFromSuperview];
        [actView release];
    });
});

}
SachinVsSachin
  • 6,401
  • 3
  • 33
  • 39
0

If you'll showing the images loaded from server on UI, then

try SDWebImageView, can be used with UIButton or UIImageView, very easy and efficient.

example,

[yourImageView setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
               placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

Read how to use it?

Okay, now for multiple images, you may need to run a loop, if you've a common base url for all your pictures (on server) something like http://yoururl/server/pictures/1.png will be replace by 2.png 3.png ... n.png, or you get different urls for pictures need to pass that url, you can load it into imageview objects, and later save them into document directory (remember, SDWebImageView by default doing this work for you). You can turn this off too.

P.S. It will load images once and stored into local (in cache) it self, next time when you pass the same image url, it won't load from server and directly load the image from local.

Hemang
  • 26,840
  • 19
  • 119
  • 186
0

Try using this code.

 NSURL* url = [NSURL URLWithString:@"http://imageAddress.com"];
 NSURLRequest* request = [NSURLRequest requestWithURL:url];


[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse * response,
    NSData * data,
    NSError * error) {
if (!error){
        // do whatever you want with directory or store images.
    NSImage* image = [[NSImage alloc] initWithData:data];

}

}];
Vinayak Kini
  • 2,919
  • 21
  • 35
0

Use this code to download the image using URL and store in document directory. Iterate the logic for set of images to download and store.

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
        NSString *imageURL = @"http://sampleUrl";
        NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
        UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]]];

        NSString *imagePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"Image1.png"]];
        if(image != NULL)
        {
            //Store the image in Document
            NSData *imageData = UIImagePNGRepresentation(image);
            [imageData writeToFile: imagePath atomically:YES];
        }
Ganapathy
  • 4,594
  • 5
  • 23
  • 41