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

标签 xcode swift crash

对于具有持久状态的 OS X 应用程序,是否可以通过编程方式检测应用程序上次打开、崩溃或意外关闭的时间? (因此我可以执行一些操作来确保应用程序处于一致的状态)

最佳答案

您可以按照描述使用NSSetUncaughtExceptionHandler here .

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

关于xcode - 在 XCode/swift 中检测应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35261259/

相关文章:

ios - 从 Table View Controller 切换到 Master Detail Controller

ios - 设备日志未出现在 Xcode 中

ios - 何时在自定义 UIVIew 中添加 CAAnimation?

Android 原生崩溃

ios - GCD/NSOperationQueue EXC_BAD_ACCESS

ios - 如何修复 Apple Mach-O 链接器 (ld) 错误组 - ld : library not found for -lFBSDKCoreKit

ios - 选择图片时 UIImagePickerController 卡住

ios - 如何检查是否支持触觉引擎 (UIFeedbackGenerator)

使用自定义枚举时 Xcode 经常崩溃

python - 带有 tensorflow-gpu 的 Keras 完全卡住了 PC