Mike Deluca
Mike Deluca

Reputation: 1210

Why does writing to plist fail in Swift?

I am trying to write the contents of an NSMutableDictionary to a plist in Swift 3. This is the structure I used in Objective-C but it does not work in Swift. When running the code below, it results in an error. Does anyone have any idea what might be wrong here?

let array1 = "\(Int(Value1))"
let array2 = "\(Int(Value2))"

let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let plistpath = NSURL(fileURLWithPath: paths[0]).appendingPathComponent("myplist9.plist")!.absoluteString

let dictionary: NSMutableDictionary = ["String":"String"]
dictionary["Value 1"] = array1
dictionary["Value 2"] = array2

if dictionary.write(toFile: plistpath, atomically: false) {
    print("Success")
}
else {
    print("Error")
}

Upvotes: 1

Views: 203

Answers (1)

rmaddy
rmaddy

Reputation: 318794

You can't get convert an NSURL to a file path using the absoluteString method. You need to use the path method.

Change:

let plistpath = NSURL(fileURLWithPath: paths[0]).appendingPathComponent("myplist9.plist")!.absoluteString

to:

let plistpath = NSURL(fileURLWithPath: paths[0]).appendingPathComponent("myplist9.plist")!.path

And since you are using Swift 3, use URL, not NSURL.

let plistpath = URL(fileURLWithPath: paths[0]).appendingPathComponent("myplist9.plist")!.path

Or you can use the NSDictionary write(to:atomically:) method that takes a URL.

Upvotes: 3

Related Questions