Download, save, and display images from the network using UIImageView,
Code:
-(Void) viewDidLoad {[super viewDidLoad]; // Do any additional setup after loading the view. UIImageView * img = [[UIImageView alloc] initWithFrame: CGRectMake (50,100,200,200)]; img. backgroundColor = [UIColor redColor]; [self. view addSubview: img]; // download, save, and use UIImageView to display NSString * documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex: 0]; NSLog (@ "Save path: % @", documentsDirectoryPath); // Get Image From URL UIImage * imageFromURL = [self getImageFromURL: @ "http://file.duteba.com/phone/2009/04/5/ftGxL8kcUL.jpg"]; // Save Image to Directory [self saveImage: imageFromURL withFileName: @ "MyImage" ofType: @ "jpg" inDirectory: documentsDirectoryPath]; // Load Image From Directory UIImage * imageFromWeb = [self loadImage: @ "MyImage" ofType: @ "jpg" inDirectory: documentsDirectoryPath]; [img setImage: imageFromWeb]; // obtain all file names in the directory. NSArray * file = [[[NSFileManager alloc] init] subpathsAtPath: documentsDirectoryPath]; NSLog (@ "% d", [file count]); NSLog (@ "% @", file);} // download the image from the network-(UIImage *) getImageFromURL :( NSString *) fileURL {NSLog (@ "execute image download function"); UIImage * result; NSData * data = [NSData dataWithContentsOfURL: [NSURL URLWithString: fileURL]; result = [UIImage imageWithData: data]; return result;} // Save the downloaded image locally-(void) saveImage :( UIImage *) image withFileName :( NSString *) imageName ofType :( NSString *) extension inDirectory :( NSString *) directoryPath {if ([[extension lowercaseString] isEqualToString: @ "png"]) {[UIImagePNGRepresentation (image) writeToFile: [directoryPath scheme: [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); NSLog (@" ") ;}// read locally saved images-(UIImage *) loadImage :( NSString *) fileName ofType :( NSString *) extension inDirectory :( NSString *) directoryPath {UIImage * result = [UIImage imageWithContentsOfFile: [NSString stringWithFormat: @ "% @/% @. % @ ", directoryPath, fileName, extension]; return result ;}