【问题标题】:Can't get plist URL in Swift无法在 Swift 中获取 plist URL
【发布时间】:2016-01-31 19:24:13
【问题描述】:

我真的对这个感到困惑。网上有很多问题在问“如何在 Swift 中从我的 plist 文件中获取信息?”并且到处都发布了相同的答案:

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

然而,这条生产线总是为我产生nil。我已将 Config 替换为默认 plist 文件中的其他组件,但也得到了 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

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

【问题讨论】:

    标签: swift plist


    【解决方案1】:

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

    斯威夫特 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"]
    

    斯威夫特 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"]
    

    【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多