Swift 5: How to read variables in plist files?

Viewed 6148

I searched a way (or a template) how to read variables which are stored in plist files. I saw a few codes, but no code worked with the newest Swift version.

I'm new to Swift, I actually don't check exactly how it works.. Could anyone be so nice and give me an example?

I have a CollectionView and want to display the strings in my plist file. That's my plist file:

For every animal key (dictionary type) two sub keys (name and picture). Root --> Animals --> Animals1

All Keys expept "name" and "picture" are dictionaries. Now I want to get the dictionaries and show the name and the picture in my collection view. Later I will add more vars. I hope it's understandable :'D

The incomplete code I have:

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    let path = Bundle.main.path(forResource: "Animals", ofType:"plist")!
    let dict = NSDictionary(contentsOfFile: path)
    SortData = dict!.object(forKey: "Animals") as! [Dictionary]
}
2 Answers

Your property list format is not very convenient. As you want an array anyway create the property list with an array for key animals (and name all keys lowercased)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>animals</key>
    <array>
        <dict>
            <key>name</key>
            <string>Tiger</string>
            <key>picture</key>
            <string>tiger_running</string>
        </dict>
        <dict>
            <key>name</key>
            <string>Jaguar</string>
            <key>picture</key>
            <string>jaguar_sleeping</string>
        </dict>
    </array>
</dict>
</plist>

Then create two structs

struct Root : Decodable {
    let animals : [Animal]
}

struct Animal : Decodable {
    let name, picture : String
}

and the data source array

var animals = [Animal]()

And decode the stuff

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    let url = Bundle.main.url(forResource: "Animals", withExtension:"plist")!
    do {
        let data = try Data(contentsOf: url)
        let result = try PropertyListDecoder().decode(Root.self, from: data)
        self.animals = result.animals
    } catch { print(error) }
}

PropertyListDecoder and PropertyListSerialization are state of the art in Swift. The NSDictionary/NSArray API is objective-c-ish and outdated.

You could use PropertyListSerialization or NSDictionary as you have done. Here most probably you have gone wrong due to some other reason.

class ViewController: UIViewController {

    var animals = [String: Any]()

    override func viewDidLoad() {
        super.viewDidLoad()

        fetchAnimals() // or fetchPropertyListAnimals()
        fetchPropertyListAnimals()
    }

    func fetchAnimals() {

        guard let path = Bundle.main.path(forResource: "Animals", ofType: "plist") else {
            print("Path not found")
            return
        }

        guard let dictionary = NSDictionary(contentsOfFile: path) else {
            print("Unable to get dictionary from path")
            return
        }

        if let animals = dictionary.object(forKey: "Animals") as? [String: Any] {
            self.animals = animals
        } else {
            print("Unable to find value for key named Animals")
        }
    }

    func fetchPropertyListAnimals() {
        var propertyListFormat =  PropertyListSerialization.PropertyListFormat.xml
        guard let path = Bundle.main.path(forResource: "Animals", ofType: "plist") else {
            print("Path not found")
            return
        }
        guard let data = FileManager.default.contents(atPath: path) else {
            print("Unable to get data from path")
            return
        }
        do {
            if let animals = try PropertyListSerialization.propertyList(from: data, options: .mutableContainersAndLeaves, format: &propertyListFormat) as? [String: Any] {
                self.animals = animals
            } else {
                print("Unable to find value for key named Animals")
            }

        } catch {
            print("Error reading plist: \(error), format: \(propertyListFormat)")
        }
    }
}
Related