我是 iOS 新手,需要创建一个 NSURL 指向我已复制到应用程序根目录中的图像(即与 AppDelegate 和我的 Controller 类文件所在的目录相同)。
给出以下代码,为什么图像不加载以及如何获得要验证的 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
加载似乎不起作用。
最佳答案
你搞混了URLWithString
和 fileURLWithPath
//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"];
关于IOS - 无法在应用程序的根目录加载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25443153/