Swift:本机检测应用程序是否崩溃 [英] Swift: Natively Detect if App has Crashed
问题描述
我已经四处搜索,但尚未找到不将我引向 3rd 方服务的答案.我不需要任何复杂的东西,只需在 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 = true
应用代理
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:本机检测应用程序是否崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!