Swift:本机检测App是否已崩溃 [英] Swift: Natively Detect if App has Crashed
问题描述
我已经四处寻找,但尚未找到一个不会引导我转向第三方服务的答案。我不需要任何复杂的东西,只是为了在 NSUserDefaults
中保存一个值,所以当下一个应用程序打开时,我会显示一条警告,说明应用程序已崩溃。
I have searched around, but have yet to find an answer that doesn't direct me towards a 3rd party service. I do not need anything intricate, just to save a value in NSUserDefaults
so when the app opens next, I can display an alert saying the app has crashed.
谢谢。
推荐答案
感谢@RyanCollins的一点帮助,我能够我自己解决问题。 App Delegate中的函数 applicationWillTerminate
仅在应用正常关闭时运行。本机检测应用程序崩溃的代码如下所示。
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.
全局定义的变量
let crashedNotificationKey = "com.stackoverflow.crashNotificationKey"
var crashedLastTime : Bool! = 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
}
根视图控制器
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)
}
这篇关于Swift:本机检测App是否已崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!