erdemgc
erdemgc

Reputation: 1721

Unable to Write Array of Dict to Plist File

I am unable to write array of dicts into plist file. I can write Dictionary to plist file is ok.

My code is as follows; It is always not success

    if var plistArray = NSMutableArray(contentsOfFile: path)
    {

        plistArray.add(dict)

        let success = plistArray.write(toFile: path, atomically: true)

        if success
        {
            print("success")
        }
        else
        {
            print("not success")
        }

    }

What might be wrong?

BR,

Erdem

Upvotes: 1

Views: 1351

Answers (2)

vadian
vadian

Reputation: 285150

First of all do not use NSMutableArray in Swift at all, use native Swift Array.

Second of all don't use the Foundation methods to read and write Property List in Swift, use PropertyListSerialization.

Finally Apple highly recommends to use the URL related API rather than String paths.


Assuming the array contains

[["name" : "foo", "id" : 1], ["name" : "bar", "id" : 2]]

use this code to append a new item

let url = URL(fileURLWithPath: path)

do {
    let data = try Data(contentsOf: url)
    var array = try PropertyListSerialization.propertyList(from: data, format: nil) as! [[String:Any]]
    array.append(["name" : "baz", "id" : 3])
    let writeData = try PropertyListSerialization.data(fromPropertyList: array, format: .xml, options:0)
    try writeData.write(to: url)
} catch {
    print(error)
}

Consider to use the Codable protocol to be able to save property list compliant classes and structs to disk.

Upvotes: 4

Harsh
Harsh

Reputation: 2908

I think you are missing the serialization part, you need to convert your plist file to data first and then write to file.

 let pathForThePlistFile = "your plist path"
    // Extract the content of the file as NSData
    let data =  FileManager.default.contents(atPath: pathForThePlistFile)!
    // Convert the NSData to mutable array
    do{
        let array = try PropertyListSerialization.propertyList(from: data, options: PropertyListSerialization.MutabilityOptions.mutableContainersAndLeaves, format: nil) as! NSMutableArray
        array.add("Some Data")
        // Save to plist
        array.write(toFile: pathForThePlistFile, atomically: true)
    }catch{
        print("An error occurred while writing to plist")
    }

Upvotes: 0

Related Questions