IOS: Download image from URL and save to device

I am trying to download an image from the URL http://a3.twimg.com/profile_images/414797877/05052008321_bigger.jpg

I use the following code, but the image is not saved on the device. I want to know what I'm doing wrong.

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://a3.twimg.com/profile_images/414797877/05052008321_bigger.jpg"]]; [NSURLConnection connectionWithRequest:request delegate:self]; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:@"pkm.jpg"]; NSData *thedata = NULL; [thedata writeToFile:localFilePath atomically:YES]; UIImage *img = [[UIImage alloc] initWithData:thedata]; 
+43
ios iphone cocoa-touch image ipad
Mar 23 '10 at 10:44
source share
9 answers

If you set theData to nil , what do you expect from writing to disk?

What you can use is NSData* theData = [NSData dataWithContentsOfURL:yourURLHere]; to load data from disk and then save it using writeToFile:atomically: If you need more control over the boot process or have it in the background, check out the NSURLConnection documentation and related manuals.

+34
Mar 23 '10 at 10:54
source share
— -

I definitely have what you are looking for.

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 { NSLog(@"Image Save Failed\nExtension: (%@) is not recognized, use (PNG/JPG)", extension); } } 

Upload 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]; 
+95
Jun 03 '12 at 19:21
source share

This is the code to download the image from the URL and save the image on the device, and this is a link link.

  NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://a3.twimg.com/profile_images/414797877/05052008321_bigger.jpg"]]; [NSURLConnection connectionWithRequest:request delegate:self]; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *localFilePath = [documentsDirectory stringByAppendingPathComponent:@"pkm.jpg"]; NSData *thedata = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://a3.twimg.com/profile_images/414797877/05052008321_bigger.jpg"]]; [thedata writeToFile:localFilePath atomically:YES]; 
+9
Jun 03 '12 at 18:41
source share

Get image from URL

 -(UIImage *) getImageFromURL:(NSString *)fileURL { UIImage * result; NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]]; result = [UIImage imageWithData:data]; return result; } 

This worked great for me, but I ran into memory issues with CFData (store). Fixed this with autoreleasepool:

  -(UIImage *) getImageFromURL:(NSString *)fileURL { @autoreleasepool { UIImage * result; NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]]; result = [UIImage imageWithData:data]; return result; } } 
+4
May 10 '13 at
source share

Hey. Clearly, you are writing NULL data to your file.

In your code expression NSData * thedata = NULL; indicates that you are assigning NULL to your data.

You also write NULL data to your file.

Check your code again.

+2
Mar 23 '10 at 10:54
source share

Since we are now on iOS6, you no longer need to write images to disk.
Starting with iOS5, you can now set "allow external storage" to the coredata binary attribute. According to the notes on the release of apples, this means the following:

Small data values, such as thumbnails of images, can be effectively stored in databases, but photos with large volumes or other media are best handled directly from the file system. Now you can specify that the value of the managed attribute of an object can be saved as an external record - see setAllowsExternalBinaryDataStorage: When enabled, Core Data heuristically decides on a cost basis if it should store data directly in the database or store the URI for a separate file that it manages for you. You cannot query based on the contents of a binary data property if you use this option.

+2
03 Dec '12 at 22:24
source share
 -(IBAction)BtnDwn:(id)sender { [self.actvityIndicator startAnimating]; NSURL *URL = [NSURL URLWithString:self.dataaArray]; NSURLRequest *request = [NSURLRequest requestWithURL:URL]; NSURLSession *session = [NSURLSession sharedSession]; NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) { NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]; NSURL *documentsDirectoryURL = [NSURL fileURLWithPath:documentsPath]; NSURL *documentURL = [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]]; BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:[documentURL path]]; if (exists) { NSLog(@"not created"); UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Download" message:@"sory,file already exists" delegate:nil cancelButtonTitle:@"cancel" otherButtonTitles:nil]; [alert show]; } else { [[NSFileManager defaultManager] moveItemAtURL:location toURL:documentURL error:nil]; UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Download" message:@"Succesfully downloaded" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [self.actvityIndicator stopAnimating]; NSLog(@"wait downloading......"); [alert show]; } }]; [downloadTask resume]; } 
+1
Mar 27 '15 at 7:14
source share

Here is an example of how I load banners into my application. I load images in the background and most of my applications do not use reference counting, so I release objects.

 - (void)viewDidLoad { [super viewDidLoad]; [NSThread detachNewThreadSelector:@selector(loadImageInBackground) toTarget:self withObject:nil]; } - (void) loadImageInBackground { NSURL *url = [[NSURL alloc] initWithString:@"http://yourImagePath.png"]; NSData *data = [[NSData alloc] initWithContentsOfURL:url]; [url release]; UIImage *result = [[UIImage alloc] initWithData:data]; [data release]; UIImageView *banner_ImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 50)]; [self.view addSubview:banner_ImageView]; banner_ImageView.image = result; [result release]; } 
0
Apr 05
source share

Here's how you can save an image asynchronously in Swift:

 requestImage("http://www.asdf.com/89asdf.gif") { (image) -> Void in let myImage = image } func requestImage(url: String, success: (UIImage?) -> Void) { requestURL(url, success: { (data) -> Void in if let d = data { success(UIImage(data: d)) } }) } func requestURL(url: String, success: (NSData?) -> Void, error: ((NSError) -> Void)? = nil) { NSURLConnection.sendAsynchronousRequest( NSURLRequest(URL: NSURL (string: url)!), queue: NSOperationQueue.mainQueue(), completionHandler: { response, data, err in if let e = err { error?(e) } else { success(data) } }) } 

It is included as a standard feature in my repo:

https://github.com/goktugyil/EZSwiftExtensions

0
Dec 01 '15 at 20:11
source share



All Articles