如何获取图像的路径形式主要资源的资源

Bha*_*n_m 7 iphone xcode ios6 swift

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

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

结果:

(null)
Run Code Online (Sandbox Code Playgroud)

我也试过这段代码

NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"myImage1" ofType:@"png"];
Run Code Online (Sandbox Code Playgroud)

但是这段代码给了我(null)结果.

myImage1 的道路是 Resources/images/myImage1.png

我不知道是什么问题.请提出一些修正建议.

Bha*_*n_m 11

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

  • 右键单击xcode中的项目并选择Add Files to "project name".
  • 从计算机本地磁盘中选择您的映像文件.
  • 在弹出的窗口中确保您选择Copy items into destination group's folder和Create Folder References for any added folders和Add to targets.
  • 点击Add.

然后用波纹管代码我可以检索我的图像.

对于Objective-C版本

[[NSBundle mainBundle] pathForResource:@"imageName" ofType:@"png"];
Run Code Online (Sandbox Code Playgroud)

对于Swift 4.0版本

Bundle.main.path(forResource: "imageName", ofType: "png")
Run Code Online (Sandbox Code Playgroud)


Dha*_*ekh 7

为灵魂....

转至:目标 - >"构建阶段" - >"复制捆绑资源"然后在此处添加该特定文件.

清理项目并运行.有用.

还看到......

NSBundle pathForResource inDirectory给出nil

并检查......

NSString *path = [[NSBundle mainBundle] resourcePath];
NSFileManager *fm = [NSFileManager defaultManager];
NSError *error = [[NSError alloc] init];
NSArray *directoryAndFileNames = [fm contentsOfDirectoryAtPath:path error:&error];
Run Code Online (Sandbox Code Playgroud)

打印此directoryAndFileNames的所有值,并检查您的文件名是否存在....