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])
}
}
}
Post
Replies
Boosts
Views
Activity
The MetricKit implementation is pretty straight forward. I am testing it now for a couple of days, but I never saw any report passed to my test apps. (implemented it in an empty app that just crashes every now and then and in a product of ours)
The function 'didReceive' is never called and each time I am asking 'MXMetricManager.shared.pastDiagnosticPayloads' I get an empty collection.
So that is the secret here? Is MetricKit not working for development builds? Or are there other factors/requirements not meet?
import Foundation
import MetricKit
class CrashDetection: NSObject, MXMetricManagerSubscriber {
@objc static let shared = CrashDetection()
@objc private override init() { }
internal static var crashDidOccur: Bool {
get { UserDefaults.standard.bool(forKey: crashDidOccurKey) ?? false }
set { UserDefaults.standard.set(newValue, forKey: crashDidOccurKey) }
}
@objc func start() {
MXMetricManager.shared.add(self)
}
@objc func stop() {
MXMetricManager.shared.remove(self)
}
func didReceive(_ payloads: [MXDiagnosticPayload]) {
let crashDiagnostics = payloads.compactMap({ $0.crashDiagnostics })
CrashDetection.crashDidOccur = crashDiagnostics.isEmpty == false
}
}