2016-05-13 73 views
3

我已經四處搜索,但還沒有找到一個答案,並沒有指示我轉向第三方服務。我不需要任何複雜的內容,只需要在NSUserDefaults中保存一個值,以便下次打開應用程序時,我可以顯示一條警報,告知應用程序已崩潰。Swift:本地檢測應用是否已經崩潰

謝謝。

+0

看看:HTT P://stackoverflow.com/questions/10885313/detect-app-crashed-during-load-last-time-it-was-run –

回答

9

感謝來自@RyanCollins一點點幫助,我是能夠解決自己的問題。應用程序委託中的功能applicationWillTerminate僅在應用程序正常關閉時運行。本機檢測應用程序崩潰的代碼如下所示。

的全局變量

let crashedNotificationKey = "com.stackoverflow.crashNotificationKey" 
var crashedLastTime : Bool! = 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) 
} 
+0

非常好的答案! – Leyton

+0

很高興你找到適合你的東西! –

+0

尚未測試,但我認爲這裏有一個錯誤。在應用程序didFinishLaunchingWithOptions函數中檢查crashedLastTime的值後,始終將存儲的布爾值設置爲「true」。例如:prefs.setBool(true,forKey:「crash」) – Awesomeness

1

問題是,如果應用程序崩潰,那麼它不能運行代碼寫入NSUserDefaults。

我所知道的最好的解決辦法是使用PLCrashReporter(https://plcrashreporter.org

+0

是否有一個函數或任何會運行,如果應用程序正常關閉?例如,'applicationWillResignActive',但即使應用程序崩潰,它也會運行。 –

+0

是的,在您的應用程序委託中,有像'applicationWillTerminate'和'applicationDidEnterBackground'這樣的函數可以做到這一點。 –

+0

我會調查並回復你。 –