I am trying to get simple crash detection working. Ten years ago was that no problem with Obj-C thankss to the UncaughtExceptionHandler. But Swift needs more work and I am not sure I am on the right path after I the TheEskimos posts.
I tried the following implementation, based on other approaches and comments. To my surprise it seems not to get called. Any idea what I am missing or doing wrong?
import Foundation
class CrashDetection: NSObject {
private static let observedSignals = [SIGABRT, SIGILL, SIGSEGV, SIGFPE, SIGBUS, SIGPIPE, SIGTRAP]
private static var previousSignalHandlers: [Int32:(@convention(c) (Int32) -> Void)] = [:]
@objc class func start() {
NSSetUncaughtExceptionHandler(CrashDetection.recieveException)
observedSignals.forEach { signalType in
let oldHandler = signal(signalType, CrashDetection.recieveSignal)
CrashDetection.previousSignalHandlers[signalType] = oldHandler
}
}
private static let recieveException: @convention(c) (NSException) -> Swift.Void = {
(recieveException) -> Void in
UserDefaults.standard.setValue(true, forKey: "crashDidOccur")
}
private static let recieveSignal: @convention(c) (Int32) -> Void = {
(recievedSignal) -> Void in
UserDefaults.standard.setValue(true, forKey: "crashDidOccur")
NSSetUncaughtExceptionHandler(nil)
observedSignals.forEach { signalType in
signal(signalType, previousSignalHandlers[signalType])
}
}
}