Search code examples
iosswift2plist

plist file gets written in swift 1.2 but its not get written or works in swift 2.0, what should i do?


I had written a code when i was working with swift 1.2 which its function is loading and saving the data from plist. it was working fine with swift 1.2 but now that im working on swift 2. the code still loads the value but it doesnt save the value. i run the application on device and not the simulator.

you can see the codes below:

 func loadGameData() {

    let path = NSBundle.mainBundle().pathForResource("GameData", ofType: "plist")!

    let myDict = NSDictionary(contentsOfFile: path)

    if let dict = myDict {

        highscore = dict.objectForKey("highscore")!


    } else {
        print("WARNING: Couldn't create dictionary from GameData.plist! Default values will be used!")
    }
}

func saveGameData() {
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
    let documentsDirectory = paths.objectAtIndex(0) as! NSString
    let path = documentsDirectory.stringByAppendingPathComponent("GameData.plist")
    let dict: NSMutableDictionary = ["XInitializerItem": "DoNotEverChangeMe"]



    dict.setObject(highscore.integerValue, forKey: "highscore")

    //writing to GameData.plist

    dict.writeToFile(path, atomically: true)

    let resultDictionary = NSMutableDictionary(contentsOfFile: path)
    print("Saved GameData.plist file is --> \(resultDictionary?.description)")

}

the console message after saving the code is:

Saved GameData.plist file is --> Optional("{\n    XInitializerItem = DoNotEverChangeMe;\n    highscore = 25;\n}")

does anyone know a different code which works with swift 2 ? this one worked fine with the previous versions.

Tnx for the help


Solution

  • Problem is you are reading from Main bundle while writing into Documents directly.

    Reading Path: NSBundle.mainBundle().pathForResource("GameData", ofType: "plist")!

    Writing Path: NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray

    To fix this, change your reader code like:

    func loadGameData() {
       let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray
       let documentsDirectory = paths.objectAtIndex(0) as! NSString
       let path = documentsDirectory.stringByAppendingPathComponent("GameData.plist")
    
       let myDict = NSDictionary(contentsOfFile: path)
    
       if let dict = myDict {
          highscore = dict.objectForKey("highscore")!
       } else {
          print("WARNING: Couldn't create dictionary from GameData.plist! Default values will be used!")
       }
    }