【发布时间】:2013-05-26 08:50:30
【问题描述】:
我正在尝试从 NSUrl imageURL 下载图像,并通过添加 @2x; 将其显示在具有视网膜像素密度的 UIImageView 中。这将在 iPhone 4 或更高版本上显示。我在这里使用了一些代码:How do I download and save a file locally on iOS using objective C?
当我启动它时,它在 imageView 上什么也没有显示,最后 NSLog 行打印出图像的一些非常小的尺寸,表明它并没有真正下载一个。除了错误检查非常糟糕之外,我的代码还有什么问题?
- (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];
}
编辑:好的,我解决了这个问题。我觉得我好笨。我应该放的
imageData = [NSData dataWithContentsOfFile:@filePath];
并将 filePath 放入范围内,而不是仅放入 @"0@2x.png"。
【问题讨论】:
-
我建议使用 AFNetworking。此外,dataWithContentsOfURL 是一个同步调用,因此您应该只在后台线程上运行的代码中使用它。
标签: ios iphone objective-c uiimageview retina-display