Swift:本机检测App是否已崩溃

我已经四处寻找,但还没有找到一个不会引导我去第三方服务的答案。 我不需要任何复杂的东西,只是为了在NSUserDefaults保存一个值,所以当应用程序下一次打开时,我可以显示一条警告说应用程序崩溃了。

谢谢。

感谢@RyanCollins的一点帮助,我能够自己解决问题。 App Delegate中的函数applicationWillTerminate仅在应用正常关闭时运行。 本机检测应用程序崩溃的代码如下所示。

全局定义的变量

 let crashedNotificationKey = "com.stackoverflow.crashNotificationKey" var crashedLastTime : Bool! = true 

App代表

 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 } 

根视图控制器

 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) } 

问题是,如果应用程序崩溃了,那么就无法运行代码来写入NSUserDefaults。

我所知道的最佳解决方案是使用PLCrashReporter( https://plcrashreporter.org