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

标签 ios objective-c iphone

我是 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加载似乎不起作用。

最佳答案

你搞混了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"];

关于IOS - 无法在应用程序的根目录加载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25443153/

相关文章:

ios - 如何从 Storyboard中的 appdelegate 推送 viewcontroller

objective-c - 如何从另一个 NSString 中删除 NSString 的文本

ios - 为什么无法访问 view.center.x/y

ios - 我在 iOS 中收到错误的通知时间?

javascript - WebRTC 在 iOS 中与 OWN 服务器的集成

ios - cocos2d 场景与图层

iphone - YouTube视频无法在iPhone中使用

iphone - slider 在时间段内自动递增

iphone - 固定位置 div 下方的链接在 iPhone 上是可点击的

ios - 可以并排运行 Fabric 和 TestFlight 应用程序吗?