在XCode / swift中检测应用程序崩溃

时间:2016-02-08 01:27:59

标签: xcode swift crash

对于具有持久状态的OS X应用程序,无论如何都要以编程方式检测应用程序上次打开,崩溃或意外关闭? (所以我可以执行一些操作来确保应用程序处于一致状态)

1 个答案:

答案 0 :(得分:0)

您可以按照here所述使用NSSetUncaughtExceptionHandler

    NSSetUncaughtExceptionHandler { exception in
        print("Exception: \(exception.name) 
                          \(exception.reason!)
                          \(exception.description)")
        print(exception.callStackSymbols)
    }

我正在使用的代码是......

NSSetUncaughtExceptionHandler {
    exception in
    ExceptionManager.handle(exception)
}

ExceptionManager类包含...

class ExceptionManager {

    class func handle(exception: NSException) {
        var exceptions = [ExceptionItem]()
        if let items = NSUserDefaults.standardUserDefaults().arrayForKey("UncaughtExceptions") as? [NSData] {
            for item in items {
                if let exception = NSKeyedUnarchiver.unarchiveObjectWithData(item) as? ExceptionItem {
                    exceptions.append(exception)
                }
            }
        }

        let newItem = ExceptionItem(NSDate(), exception)
        exceptions.insert(newItem, atIndex: 0)
        if exceptions.count > 5 { // Only keep the last 5 exceptions
            exceptions = Array(exceptions[0..<5])
        }

        var items = [NSData]()
        for e in exceptions {
            let item = NSKeyedArchiver.archivedDataWithRootObject(e) as NSData
            items.append(item)
        }
        NSUserDefaults.standardUserDefaults().setObject(items, forKey: "UncaughtExceptions")
    }