ios - 从非 mainBundle 的 NSBundle 获取文件路径

标签 ios swift nsbundle

我正在尝试获取 plist 文件的 pathForResource,当文件在 mainBundle 中时很容易,我使用了:

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

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

最佳答案

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

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
    }
}

另一方面,如果您确实有您的包的路径标识符,您可以使用:

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

or

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

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

关于ios - 从非 mainBundle 的 NSBundle 获取文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31290219/

相关文章:

iOS NSMutableURLRequest 授权 header

ios - 单元格中的破坏约束

ios - 如何用 Observable 包装异步函数

ios - 将文件/文件夹从 Web 同步到 iOS 应用程序包

ios - NSBundle 的 pathForDirectory 方法?

ios - 意外发现标签和表格 View 为零

ios - 我如何从 viewdidload 函数中的 GET 请求函数快速排列

ios - Facebook 在 iOS 上登录错误的应用程序

iphone - 使用 C++ 在 iOS 应用程序中找不到的文件夹中的文件

objective-c - OCMock 不 stub NSBundle 方法