4

I'm trying to download an image from the NSUrl imageURL and display it in a UIImageView with retina pixel density by adding the @2x; this is to be displayed on an iPhone 4 or later. I've used some code from here: How do I download and save a file locally on iOS using objective C?

It shows nothing on the imageView when I start it, and the last NSLog line prints out some really tiny dimensions for the image, suggesting that it didn't really download one. What is wrong with my code besides it having really bad error checking?

- (void) presentImage: (NSURL*) imageURL{
NSData * imageData = [NSData dataWithContentsOfURL:imageURL];
NSLog([imageURL description]);

if ( imageData )
{
    NSArray   *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString  *documentsDirectory = [paths objectAtIndex:0];

    NSString  *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"0@2x.png"];
    [imageData writeToFile:filePath atomically:YES];
}
else NSLog(@"Error when loading image!!!");

imageData = [NSData dataWithContentsOfFile:@"0@2x.png"];
UIImage *image = [[UIImage alloc] initWithData: imageData];
NSLog(@"%f1 x %f2", image.size.width, image.size.height);
[self.imageView setImage: image];

}

EDIT: OK, I fixed that. I feel stupid. I was supposed to put in

imageData = [NSData dataWithContentsOfFile:@filePath];

and put filePath in scope nstead of just putting in @"0@2x.png".

Community
  • 1
  • 1
sudo
  • 5,604
  • 5
  • 40
  • 78
  • I would suggest using AFNetworking. Also, dataWithContentsOfURL is a synchronous call so you should only use it in code running on a background thread. – Marcin Kuptel May 30 '13 at 17:01

1 Answers1

4

You're overcomplicating the issue I think. Use this method:

+ (UIImage *)imageWithData:(NSData *)data scale:(CGFloat)scale

And set the scale to 2.0 when you have a retina image.

-(void)presentImage:(NSURL*)imageURL {
    NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
    UIImage *image = [UIImage imageWithData:imageData scale:2.0];
    [self.imageView setImage: image];
}
mprivat
  • 21,582
  • 4
  • 54
  • 64
  • Oh, perfect! Even after I fixed my code, it still wasn't working right. My code definitely seemed overcomplicated, but I thought that that's what it would take. – sudo May 30 '13 at 17:08