【问题标题】:Get file path from a NSBundle which is not the mainBundle从不是 mainBundle 的 NSBundle 获取文件路径
【发布时间】:2015-07-08 10:38:15
【问题描述】:

我正在尝试为plist 文件获取pathForResource,当该文件位于 mainBundle 中时,这很容易,我使用了:

let path = NSBundle.mainBundle().pathForResource("Settings", ofType: "plist")

但现在我将settings 文件移动到另一个包中,但我不知道如何获取它。我尝试使用forClassallBundles,但我是一个快速的菜鸟,并没有成功。也无法通过网络找到解决方案。似乎所有NSBundle 用法示例仅适用于mainBundle

【问题讨论】:

  • 请您在 xcode 中显示目录结构。您将文件打包从哪里移动到哪里?
  • 你知道你在哪个包中移动了资源吗?
  • 好吧,我不确定你的意思。也许我的解释不正确。我将文件目标成员身份从当前更改为名为 Kit 的嵌入式二进制文件

标签: ios swift nsbundle


【解决方案1】:

如果您不知道哪个捆绑包拥有您的资源,您可以遍历所有资源包:

let bundles = NSBundle.allBundles()

var path : String?
var myBundle : NSBundle?

for bundle in bundles {
    if let resourcePath = (bundle as! NSBundle).pathForResource("Settings", ofType: "plist") {
        path = resourcePath
        myBundle = bundle
        break
    }
}

另一方面,如果你有 pathidentifier 你可以使用你的包:

let bundle = NSBundle(path: "the-bundle-path")

or

let bundle = NSBundle(identifier: "bundle-identifier")

这与你的 Swift 编程知识水平无关,而是与 NSBundle 暴露的接口有关。您应该查看docs,看看他们是否可以帮助您。

【讨论】:

  • 已经尝试过文档...不是很有帮助。无论如何let bundle = NSBundle(identifier: "bundle-identifier") 工作!谢谢!
猜你喜欢
  • 2023-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-25
  • 2011-05-01
  • 2016-08-28
  • 2011-09-09
相关资源
最近更新 更多