Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save Data to .plist File in Swift

Tags:

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?

like image 458
trumpeter201 Avatar asked Aug 02 '14 23:08

trumpeter201


1 Answers

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) 
like image 90
trumpeter201 Avatar answered Oct 27 '22 01:10

trumpeter201