Using MetricKit
In this post, I will show you how to use MetricKit to collect and analyze performance data from your app.
What is MetricKit?
MetricKit is a framework introduced in iOS 13 that allows you to collect and analyze performance data from your app.
It provides a set of APIs to access metrics such as CPU usage, memory usage, disk I/O, and network I/O.
You can use this data to identify performance bottlenecks, optimize your app, and improve the user experience.
What metrics can you collect?
MetricKit provides APIs to collect the following metrics:
- Diagnostics for crashes
- Hangs
- Energy
- Disk writes
How to use MetricKit?
To use MetricKit in your app, you need to follow these steps:
Step 1: Import MetricKit
import MetricKit
Step 2: Register for metric updates
To receive metric updates, you need to create a class that conforms to the MXMetricManagerSubscriber
protocol and register your class with the MXMetricManager
singleton object in your app's main entry point.
@main
struct DinnerConnectApp: App {
private var metrics = MetricSubscriber()
var body: some Scene {
WindowGroup {
MyAppView()
.onAppear {
MXMetricManager.shared.add(metrics)
}
}
}
}
Step 3: Implement the MetricSubscriber protocol
We create a MetricSubscriber class that conforms to the MXMetricManagerSubscriber
protocol to receive metric payloads.
class MetricSubscriber: NSObject, MXMetricManagerSubscriber {
func didReceive(_ payloads: [MXMetricPayload]) {
print("didReceive MXMetricPayload")
guard let firstPayload = payloads.first else { return }
if let jsonString = String(
data: firstPayload.jsonRepresentation(),
encoding: .utf8
) {
print(jsonString)
} else {
print("Failed to encode")
}
}
func didReceive(_ payloads: [MXDiagnosticPayload]) {
print("didReceive MXDiagnosticPayload")
guard let firstPayload = payloads.first else { return }
if let jsonString = String(
data: firstPayload.jsonRepresentation(),
encoding: .utf8
) {
print(jsonString)
} else {
print("Failed to encode")
}
}
}
Debugging MetricKit
MetricKit will only work on a real device, not on the simulator.
To send a metric payload to your app, you can go to Debug > Simulate MetricKit Payloads in Xcode.
References/resources:
Read more
- Understanding Package.swift • 13 minutes reading time.
- SwiftLeeds 2024, Day 1 • 11 minutes reading time.
- Appril Festival 2024 • 7 minutes reading time.
Share
Share Mastodon Twitter LinkedIn Facebook