Search code examples
iosswiftplist

How do I get content of a plist file in swift?


So I created I plist file that get a list of all libs licenses on my podfile (following this tutorial: https://johncodeos.com/easy-way-to-list-third-party-libraries-licenses-in-your-ios-app/)

But now how can I get the content of this file? Every example that I used comes with a file path nil. What am I doing wrong?

Example code:

let path = Bundle.path(forResource: "Acknowledgements", ofType: "plist", inDirectory: "Licenses")

My plist file structure: plist structure

I would like to get title and footerText of every Item in my PreferenceSpecifiers. How could I do that?

PS.: I've never work with plist/bundle.setting files before, so forgive if I'm asking something dumb. I've read about but it/s still cloudy to me


Solution

  • You can use the function url(forResource:withExtension:) instead of the path. You can use this function (replace MyPlistFile.plist with the name of your file):

    // Provide the key of the entry you need to read
        func getStringValueFromPlist(forKey key: String) -> String {
            guard let fileURL = url(forResource: "MyPlistFile.plist", withExtension: nil) else {
                fatalError("Can't find \(fileName)")
            }
    
            let contents = NSDictionary(contentsOf: fileURL) as? [String: String] ?? [:]
    
            return contents[key] ?? ""
        }
    

    To get a nested dictionary, you need to change the type, from String to a dictionary type, like [String: String], then read inside that dictionary.