Can't get plist URL in Swift

元气小坏坏 提交于 2019-12-11 02:31:11

问题


I'm really confused on this one. There are dozens of questions around the web asking "How do I get info from my plist file in Swift?" and the same answer is posted everywhere:

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

However, this line produces always produces nil for me. I have replaced Config with other components found in the default plist file, but get nil as well.

I am trying to access my custom ProductIdentifiers Array like so:

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

I get a crash stating fatal error: unexpectedly found nil while unwrapping an Optional value on productArray. I have also tried this with other default plist values in place of ProductIdentifiers.

Does anyone know why this is not working for me even though there are so many posts around of people using this successfully?


回答1:


I've never heard of the OP's approach working before. Instead, you should open the Info.plist file itself, then extract values from it, like so:

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"]



回答2:


Resource represents the file name of the plist rather than its contents.

The root object of the plist is probably a dictionary.

Replace MyPlist with the real file name. This code prints the contents of the 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")
}


来源:https://stackoverflow.com/questions/35118301/cant-get-plist-url-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!