0

I want to both download, save, and display an image.

I am using this code, which DOES work when I directly load *image.

 [self.imageView setImageWithURLRequest:request placeholderImage:nil
    success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
        // Set the image
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Image.png"];

        // Save image.
        [UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES];

        UIImage * imag2e = [UIImage imageNamed: @"Image"];
        weakSelf.imageView.image = imag2e;

        [self updateZoom];
        [self updateConstraints];

        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
    }
    failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
        NSLog(@"An error occured when loading the image, %@", [error description]);
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
    }];
hunterp
  • 15,716
  • 18
  • 63
  • 115
  • 2
    What doesn't work exactly? Writing? Loading? Showing Image? Is your block in background? If that's the case, you can only update UI in main thread. – Larme Apr 08 '15 at 10:40
  • It seems that you are using AFNeworking is possible that second time your image is loaded from the cache and I don't remember if the success block is called. – Andrea Apr 08 '15 at 10:53
  • http://stackoverflow.com/questions/2499176/ios-download-image-from-url-and-save-in-device – Yuyutsu Apr 08 '15 at 12:37

1 Answers1

4

I think the error is on the line:

UIImage * imag2e = [UIImage imageNamed: @"Image"];

In the documentation for +[UIImage imageNamed:] it states:

If this is the first time the image is being loaded, the method looks for an image with the specified name in the application’s main bundle.

And the saved image is located elsewhere. E.g. try:

UIImage * imag2e = [UIImage imageWithContentsOfFile: filePath];
Mats
  • 8,528
  • 1
  • 29
  • 35