ios - 变量不会填充 plist 数据,Swift

标签 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是正确的,并且没有给出错误,所以我不知道哪里出了问题。所有其他方法都有正确的路径,但从未填充内容变量。

最佳答案

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/

相关文章:

ios - facebook sdk ios获取用户信息

arrays - FirstIndex :of: in an array of objects

ios - Swift:如何将 UITextField 可选字符串展开为 float

java - 使用 Java 创建一个 plist

ios - 为什么Swift 3对OSX和iOS版本的NSString会有不同的对待?

ios - 在 watchOS 2 扩展中创建的 Realm 浏览器中打开 Realm 文件

android - 如何管理 Azure 通知中心中的数千个应用程序用户,并且收件人每天都在变化?

ios - else if 条件不执行语句

ios - StartInterval 键如何影响启动的守护进程

objective-c - objective-c : problem with directory file