变量不会填充plist数据,Swift

时间:2017-07-31 18:55:44

标签: ios swift plist

我一直在努力将plist文件读取到我的iOS应用程序中,但到目前为止我使用的每种方法都失败了。我目前正在使用http://basememara.com/reading-values-plist-bundle-swift/中描述的方法,但我尝试的每种方法似乎都有同样的问题。

如果这是读取plist文件的代码:

/**
 Gets the contents of the specified plist file.

 - parameter plistName: property list where defaults are declared
 - parameter bundle: bundle where defaults reside

 - returns: dictionary of values
 */
public static func contentsOfFile(plistName: String, bundle: Bundle? = nil) -> [String : AnyObject] {
    let fileParts = plistName.components(separatedBy: ".")

    guard fileParts.count == 2,
        let resourcePath = (bundle ?? Bundle.main).path(forResource: fileParts[0], ofType: fileParts[1]),
        let contents = NSDictionary(contentsOfFile: resourcePath) as? [String : AnyObject]
        let contentsarray = NSArray(contentsOfFile: resourcePath)
        else { return [:] }

    return contents
}

,电话是

let values = Bundle.contentsOfFile(plistName: "Event.plist")
print(values["Item0"]) // My string value 1.

随着plist看起来像 enter image description here

变量Contents和ContentsArray(用于测试)没有任何内容。我已经验证了resourcePath是正确的,并且没有给出错误,所以我不知道出了什么问题。每个其他方法都有正确的路径,但从不填充内容变量。

1 个答案:

答案 0 :(得分:0)

if let path = Bundle.main.path(forResource: "Test", ofType: "plist") {
        let myDict = NSDictionary(contentsOfFile: path)
        print(myDict)
}

另一种方式 -

if let url = Bundle.main.url(forResource:"Test", withExtension: "plist"),
        let myDict = NSDictionary(contentsOf: url) as? [String:Any] {
        print(myDict)
}

此外,它也可能有针对目标成员资格的目标。在项目导航器中选择plist文件,然后选中File inpector的Target Membership部分。