对于具有持久状态的 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/