MetricKit and when or when not do we get reports?

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

Replies

Have you confirmed via another mechanism that your app is indeed crashing? Off the shelf crash solution, device crash file, test flight crashes, etc.

I assume that you are calling your start() method. To check this out:

  1. Run your app with Xcode with debugger attached
  2. Xcode > Debug > Simulate Metric Payloads
  3. Observe your code being invoked (or not).

I have noticed that in flavors of Xcode 14, this doesn't work to reliably give diagnostic payloads but seems to have been fixed for my setup in Xcode 15.

Once you've verified your code is wired up properly via the Xcode feature, then check your understanding/expectation about WHEN the diagnostics will be delivered to your callback below.

If you're expecting the app to crash in the background here is a tip: The MetricKit diagnostic payload callback, according to the MetricKit team via a WWDC session a few years ago, is non-launching. Do you have other features in your app that would normally launch the app in the background? If so, you should expect diagnostics periodically. If not, then you'd get them when your app was launched by the user.

If you're expecting the app to crash in the foreground, then for sure, the next time you launch it I would expect to receive the payload.