1

i have soome image (.jpg,.png etc) stored in my web server. i am building an iPhone application which can upload or download images from/to my webserver.

i can upload images to my web server.

but i can not download images from my web server to my application. How i can do it????

Mez
  • 24,430
  • 14
  • 71
  • 93
faisal
  • 475
  • 2
  • 9
  • 17

2 Answers2

3

Simplest technique by using UIKit

NSURL *url = [NSURL URLWithString: @"http://images.com/image.jpg"];
NSData *data = [NSData dataWithContentsOfURL: url];
UIImage *image = [UIImage imageWithData: data];
UIImageView *imageView = [[UIImageView alloc] initWithImage: image];
1

Get Image From URL

-(UIImage *) getImageFromURL:(NSString *)fileURL {
    UIImage * result;

    NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];
    result = [UIImage imageWithData:data];

    return result;
}

Save Image

-(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);
    }
}

Load Image

-(UIImage *) loadImage:(NSString *)fileName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath {
    UIImage * result = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.%@", directoryPath, fileName, extension]];

    return result;
}

How-To

//Definitions
NSString * documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

//Get Image From URL
UIImage * imageFromURL = [self getImageFromURL:@"http://www.yourdomain.com/yourImage.png"];

//Save Image to Directory
[self saveImage:imageFromURL withFileName:@"My Image" ofType:@"png" inDirectory:documentsDirectoryPath];

//Load Image From Directory
UIImage * imageFromWeb = [self loadImage:@"My Image" ofType:@"png" inDirectory:documentsDirectoryPath];

For more details see these links

iOS: Download image from url and save in device

http://iosdevelopertips.com/cocoa/download-and-create-an-image-from-a-url.html

Cœur
  • 37,241
  • 25
  • 195
  • 267
scan.see
  • 11
  • 1
  • 3