Can't get plist URL in Swift

2019-07-15 02:37发布

问题:

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


标签: swift plist