我一直在努力将 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.
变量 Contents 和 ContentsArray(用于测试)没有任何内容。我已经验证了resourcePath是正确的,并且没有给出错误,所以我不知道哪里出了问题。所有其他方法都有正确的路径,但从未填充内容变量。
最佳答案
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)
}
此外,它也可能与目标成员(member)资格有关。在项目导航器中选择 plist 文件,然后检查文件检查器的目标成员资格部分。
关于ios - 变量不会填充 plist 数据,Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45423351/