I am trying to save data to a plist file in swift, but the data isn't showing up as it was saved when the plist is read. This is the code I was using.
var documentsDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString var path : NSString = documentsDirectory.stringByAppendingPathComponent("data.plist") var data : NSMutableDictionary = NSMutableDictionary(contentsOfFile: path) data.setObject(self.object, forKey: "key") data.writeToFile(path, atomically: true)
Edit: I've heard that the best way to do this is write to the documents directory, so my question would be how should I write to a file in that directory?
Apparently the file is not in a writable location, so I created it in the documents directory.
var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String var path = paths.stringByAppendingPathComponent("data.plist") var fileManager = NSFileManager.defaultManager() if (!(fileManager.fileExistsAtPath(path))) { var bundle : NSString = NSBundle.mainBundle().pathForResource("data", ofType: "plist") fileManager.copyItemAtPath(bundle, toPath: path, error:nil) } data.setObject(object, forKey: "object") data.writeToFile(path, atomically: true)
Then, it has to be read from the documents directory.
var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String var path = paths.stringByAppendingPathComponent("data.plist") let save = NSDictionary(contentsOfFile: path)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With