Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 5: How to read variables in plist files?

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]
}
like image 701
Marro Avatar asked Nov 22 '25 14:11

Marro


1 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.

like image 105
vadian Avatar answered Nov 25 '25 11:11

vadian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!