IOS - 无法在应用程序的根目录下加载图像

时间:2014-08-22 08:55:56

标签: ios objective-c iphone

我是iOS新手,需要创建一个NSURL,指向我已复制到应用程序根目录中的图像(即与AppDelegate和我的控制器类文件所在的目录相同)。

给出以下代码,为什么图像没有加载&如何获得if条件进行验证(即对我的图像有NSURL引用)?

NSBundle *mainBundle = [NSBundle mainBundle];
NSString *image2AbsolutPath = [mainBundle pathForResource:@"image2" ofType:@"jpg"];
NSURL *urlToImage = [NSURL URLWithString:image2AbsolutPath];
NSError *error = nil;
if (![urlToImage checkResourceIsReachableAndReturnError:&error]) {
    NSLog(@"image2.jpg could not be reached.");
}

编辑:根据评论;创建了一个imageview并成功加载并查看了图像; self.imageView.image=[UIImage imageNamed:@"image2.jpg"];

只有NSURL加载似乎不起作用。

2 个答案:

答案 0 :(得分:3)

你混淆URLWithStringfileURLWithPath

//wrong
NSString *image2AbsolutPath = [mainBundle pathForResource:@"image2" ofType:@"jpg"];
NSURL *urlToImage = [NSURL URLWithString:image2AbsolutPath];

你使用前者但是传递它不是url字符串但是文件路径。改为后者,它会起作用

//works
NSString *image2AbsolutPath = [mainBundle pathForResource:@"image2" ofType:@"jpg"];
NSURL *urlToImage = [NSURL fileURLWithPath:image2AbsolutPath];

//but more simply
NSURL *urlToImage = [mainBundle URLForResource:@"image2" withExtension:@"jpg"];

答案 1 :(得分:2)

加载您需要使用的资源

NSURL *url = [[NSBundle mainBundle] URLForResource: @"image2" withExtension:@"jpg"];

如果您查看使用pathForResourceURLForResource方法创建的两个不同路径,您会看到NSURL路径缺少必需的file://

pathForResource:

/Users/MacbookPro/Library/Developer/CoreSimulator/Devices/02D50AC9-5AF0-4F23-8757-1AF7D3153344/data/Containers/Bundle/Application/C5775786-E473-4048-9855-A2C6AA51BB05/MyApp.app/image2.png

VS

URLForResource:

file:///Users/MacbookPro/Library/Developer/CoreSimulator/Devices/02D50AC9-5AF0-4F23-8757-1AF7D3153344/data/Containers/Bundle/Application/C5775786-E473-4048-9855-A2C6AA51BB05/MyApp.app/image2.png