How to save NSUserDefaults on applicationWillTerminate

I have an NSUserDefaults style score structure in my game and you want to keep these values ​​after the application is completed. Are there any methods that save and reload the file when reopened?

+4
source share
3 answers

not to do. Save them after each change (or, if you know that you will have many changes in a short period of time, the package will save them after the updates).

applicationWillTerminate:mostly not called in the current version of iOS (since the background information was introduced), so you should not rely on it. Also think about what will happen if your application crashes and none of the user data is saved - there will not be a good user experience.

So, don't rely on applicationWillTerminate:, ever, anything ...

+3
source

After setting the values NSUserDefaultsto applicationWillTerminatemake sure that you invoke [[NSUserDefaults standardDefaults] synchronize]that the changes are immediately flushed to disk and saved between application launches.

0
source

iOS 10.3.2, , . , "applicationWillTerminate" . .

, , , plist . .

Swift 3.0.2:

func applicationWillTerminate(_ application: UIApplication) {

    let plistPath = getPath()

    if !FileManager.default.fileExists(atPath: plistPath) {

        FileManager.default.createFile(atPath: plistPath, contents: nil, attributes: nil)

    }

    let data:NSMutableDictionary = [:]
    data.setValue("test_Value", forKey: "test_key")
    data.write(toFile: plistPath, atomically: true)
}


func getPath() -> String {
    let plistFileName = "data.plist"
    let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let documentPath = paths[0] as NSString
    let plistPath = documentPath.appendingPathComponent(plistFileName)
    return plistPath
}

func displaySavedData() {
    let plistPath = self.getPath()
    if FileManager.default.fileExists(atPath: plistPath) {
        if let savedData = NSMutableDictionary(contentsOfFile: plistPath) {
            print(savedData)
        }
    }
}

When the application is running, values ​​may be available, as shown below:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    displaySavedData()
    return true

}

As described in other answers, “applicationWillTerminate” will not be called if the application supports background mode, so this solution is useful when your application does not support background mode, and you know that killing the application causes “applicationWillTerminate”.

0
source

All Articles