1

I'm trying to detect whether or not the app crashed the last time it ran.

In applicationWillTerminate I have the following code:

let defaults = UserDefaults.standard
defaults.set(false, forKey: CRASHED_KEY)
defaults.synchronize()
saveContext()

By setting the value to false I'm instructing the app that it was closed correctly.

In application(didFinishLaunchingWithOptions) I have the following code:

let defaults = UserDefaults.standard
let crashedLastTime = defaults.bool(forKey: CRASHED_KEY)

if (crashedLastTime) {
    //Handle error
}

defaults.set(true, forKey: CRASHED_KEY)
defaults.synchronize()

By setting it to true when it launches, it will be true if it crashed.

This code is acting a bit weird when restarting the app from xCode since it apparently doesn't call applicationWillTerminate. This is not a problem however.

The problem I'm having is that in some cases it will start up and say that it crashed, even though I terminated the app properly.

Any idea as to why UserDefaults doesn't always save?

Developer
  • 736
  • 7
  • 30
  • Try this, even though it in Obj-C, you can convert to swift and use: http://stackoverflow.com/questions/16330411/ios-is-there-any-delegate-method-when-the-app-quits-due-to-any-crash – Imad Ali May 22 '17 at 07:09

0 Answers0