无法在 Swift 中获取 plist URL

Can't get plist URL in Swift

我对这个真的很困惑。网络上有几十个问题在问 "How do I get info from my plist file in Swift?",到处都是相同的答案:

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

然而,这一行总是为我生成 nil。我已经用默认 plist 文件中的其他组件替换了 Config,但也得到了 nil

我正在尝试访问我的自定义 ProductIdentifiers 数组,如下所示:

let url = NSBundle.mainBundle().URLForResource("ProductIdentifiers", withExtension: "plist")!
var productArray = NSArray(contentsOfURL: url) as! [[String:AnyObject!]]

我在 productArray 上遇到崩溃,提示 fatal error: unexpectedly found nil while unwrapping an Optional value。我也尝试用其他默认 plist 值代替 ProductIdentifiers.

有谁知道为什么这对我不起作用,尽管周围有很多人成功使用了它?

我以前从未听说过 OP 的方法有效。相反,您应该打开 Info.plist 文件本身,然后从中提取值,如下所示:

Swift 3.0+

func getInfoDictionary() -> [String: AnyObject]? {
    guard let infoDictPath = Bundle.main.path(forResource: "Info", ofType: "plist") else { return nil }
    return NSDictionary(contentsOfFile: infoDictPath) as? [String : AnyObject]
}

let productIdentifiers = getInfoDictionary()?["ProductIdentifiers"]

Swift 2.0

func getInfoDictionary() -> NSDictionary? {
    guard let infoDictPath = NSBundle.mainBundle().pathForResource("Info", ofType: "plist") else { return nil }
    return NSDictionary(contentsOfFile: infoDictPath)
}

let productIdentifiers = getInfoDictionary()?["ProductIdentifiers"]

Resource 表示 plist 的 文件名 而不是其内容。

plist 的根对象可能是一个字典。

MyPlist替换为真实的文件名。 此代码打印 plist

的内容
if let url = NSBundle.mainBundle().URLForResource("MyPlist", withExtension: "plist"), 
       root = NSDictionary(contentsOfURL: url) as? [String:AnyObject] 
{
     print(root)
} else {
    print("Either the file does not exist or the root object is an array")
}