Thanks to a little help from @RyanCollins, I was able to solve the problem myself. The function applicationWillTerminate
in the App Delegate only runs when the app closes properly. The code to natively detecting an app crash looks like this.
Globally Defined Variables
let crashedNotificationKey = "com.stackoverflow.crashNotificationKey"
var crashedLastTime = true
App Delegate
func applicationWillTerminate(application: UIApplication) {
crashedLastTime = false
prefs.setBool(crashedLastTime, forKey: "crash")
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
crashedLastTime = prefs.boolForKey("crash")
if crashedLastTime == true {
crashedLastTime = false
prefs.setBool(crashedLastTime, forKey: "crash")
NSNotificationCenter.defaultCenter().postNotificationName(crashedNotificationKey, object: self)
} else {
crashedLastTime = true
prefs.setBool(crashedLastTime, forKey: "crash")
}
return true
}
Root View Controller
override func awakeFromNib() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "crashedAlert", name: crashedNotificationKey, object: nil)
}
func crashedAlert() {
let alert = UIAlertController(title: "The app has crashed!", message: "Sorry about that! I am just a 17 year old highschooler making my first game!", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "It's cool bro.", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…