【问题标题】:How to get path of image form Resource of main bundle如何获取主包的图像形式资源的路径
【发布时间】:2013-04-17 14:36:12
【问题描述】:

我有一个 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

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

【问题讨论】:

  • 我从包中复制了文件名,所以不用担心区分大小写。

标签: iphone swift xcode ios6


【解决方案1】:

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

  • 在xcode中右键项目,选择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")

【讨论】:

    【解决方案2】:

    为了灵魂……

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

    清理项目并运行。它有效。

    还可以看看...

    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 的所有值并检查您的文件名是否存在于该目录中......

    【讨论】:

    • 我得到了文件列表,我的myImage1.png 在列表中。接下来呢??
    • 一个错误,不要分配错误,你应该把“error = nil”并传递地址。
    • "-[NSError init] 被调用;这会导致无效的 NSError 实例。它将在未来的版本中引发异常。"我尝试为您编辑,但由于某种原因,例外不是在此站点上编辑的充分理由。我永远不会理解这里管理员的逻辑。
    【解决方案3】:

    首先检查主Bundle中是否有名称为name的文件。

    没有具有这样名称的文件时,它给出null

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-09
      • 2021-04-24
      • 2020-09-09
      • 1970-01-01
      • 1970-01-01
      • 2011-09-12
      • 1970-01-01
      相关资源
      最近更新 更多