swift 如何从主包的资源中获取图像路径

nbysray5  于 2023-03-28  发布在  Swift
关注(0)|答案(4)|浏览(158)

我有一个iPhone应用程序,其中我添加了images目录(组)到Resources(组)。我想访问的图像是在images。我需要一个路径到该图像,所以我创建一个代码如下。

NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"myImage1" ofType:@"png" inDirectory:@"images"];
NSLog(@"%@", imagePath);

结果:

(null)

我也试过这个代码

NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"myImage1" ofType:@"png"];

但是这段代码给了我(null)结果。
myImage1的路径是Resources/images/myImage1.png
我不知道是什么问题。请提出一些解决办法。

cfh9epnr

cfh9epnr1#

通过以下方法添加图像解决了我的问题。

  • 右键单击xcode中的project并选择Add Files to "project name"
  • 从计算机本地磁盘中选择映像文件。
  • 在弹出窗口中,确保选择Copy items into destination group's folderCreate Folder References for any added foldersAdd to targets
  • 单击Add

然后用下面的代码,我可以检索我的图像。
对于Objective-C版本

[[NSBundle mainBundle] pathForResource:@"imageName" ofType:@"png"];

对于Swift 4.0版本

Bundle.main.path(forResource: "imageName", ofType: "png")
lmvvr0a8

lmvvr0a82#

为了灵魂....
转到:Target -〉“Build Phases”-〉“copy bundle Resources”然后在这里添加该特定文件。
清理项目并运行。它可以工作。
还能看到...
NSBundle pathForResource inDirectory gives nil

并检查...

NSString *path = [[NSBundle mainBundle] resourcePath];
NSFileManager *fm = [NSFileManager defaultManager];
NSError *error = [[NSError alloc] init];
NSArray *directoryAndFileNames = [fm contentsOfDirectoryAtPath:path error:&error];

打印这个directoryAndFileNames的所有值并检查你的文件名是否存在于其中....

xam8gpfp

xam8gpfp3#

尝试通过元数据检查一个png文件。可能该文件具有真实的的jpg格式。但不是png。

cunj1qz1

cunj1qz14#

首先,检查主Bundle中是否有名称为name的文件。
没有这样的文件名时,给出null

相关问题