Search code examples
swiftmacospathplist

How to read a multidimensional array from a .plist file in macOS?


In a macOS project I have to read the contents of a .plist file and insert it into a multidimensional array. Not having found much material for macOS, I read tutorials and questions oriented to iOS programming.

I created a code that I thought could work, but when it comes to reading the contents of the file, it fails. What am I doing wrong? Thanks.

 // Edited

 let filePath = documentDirectory + "/Docs/" + "MyFile" + ".plist"
 var resourceFileArray: NSArray?

 //load the content of the plist file
 if let path = Bundle.main.path(forResource: (filePath), ofType: "plist") {
     resourceFileArray = NSArray(contentsOfFile: path)
 }

 if let resourceFileArrayContent = resourceFileArray {
     print(resourceFileArrayContent)
 } else {
     print("error")     // it always falls here
 }

Content of the plist file:

<?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">
<array>
    <array>
        <string>One</string>
        <string>false</string>
        <string></string>
        <string></string>
        <string>false</string>
        <string>false</string>
        <string>false</string>
    </array>
</array>
</plist>

Solution

  • You cannot get that plist content as NSDictionary, you can see from the plist content that it is of type [[String]]. You can use PropertyListDecoder for Swift 4 but since you are using Swift 3, you can use PropertyListSerialization like this,

    do {
      let data = try Data(contentsOf: plistFileURL)
      let output = try PropertyListSerialization.propertyList(from: data,
                                                           options: [],
                                                           format: nil) as! [[String]]
    
    } catch {
      print("Error occurred: \(error.localizedDescription)")
    }