Automatic Screen Name Tracking with Instana for iOS Apps
Instana EUM Series
Episode 2: Automatic Screen Name Tracking with Instana for Mobile Apps
In iOS apps that are developed with Swift or Objective-C, views displayed on the screen are typically hosted in a UIViewController
or one of its subclasses. In SwiftUI, views are hosted in a UIHostingController
, which is a specialized subclass of UIViewController
.
When to Set the View Name
During the lifecycle of a UIViewController
, the viewDidAppear
method is called when a view is added to the window and becomes visible. This is the ideal time to call Instana’s setView
method to set the screen name.
How to Set the View Name
We can set the view name by using method swizzling. Method swizzling is a technique used in Objective-C and Swift (via bridging) that allows developers to change the implementation of an existing method at runtime. This approach is useful for adding functions without modifying the original method’s code. Here’s a code snippet in Swift language demonstrating this:
extension UIViewController {
@objc
func instanaViewDidAppear(_ animated: Bool) {
let viewName = "automatically picked view name"
Instana.setView(viewName)
instanaViewDidAppear(animated)
}
@objc
public static func instanaSetViewAutomatically() {
let originalSelector = #selector(UIViewController.viewDidAppear(_:))
let swizzledSelector = #selector(UIViewController.instanaViewDidAppear(_:))
let originalMethod = class_getInstanceMethod(self, originalSelector)
let swizzledMethod = class_getInstanceMethod(self, swizzledSelector)
if let originalMethod = originalMethod, let swizzledMethod = swizzledMethod {
method_exchangeImplementations(originalMethod, swizzledMethod)
}
}
}
How to Name the View
After determining when and how to set the view name, we need to decide what the view name should be. Here’s the priority for picking a proper view name:
- Accessibility Label: Use the
accessibilityLabel
of theUIViewController
if it is set. - Navigation Item Title: If the
accessibilityLabel
is not set, use thenavigationItem.title
if it is not empty. - Class Name: If neither is set, use the class name of the current
UIViewController
as the view name.
Note: Views that should not be captured, such as those directly from UIKitCore.framework
or UIKit.framework
, are skipped.
How to enable autoCaptureScreenNames
feature
Auto capture screen names feature is disabled by default in iOSAgent. To enable it, use the following snippet in Swift code:
let options = InstanaSetupOptions(autoCapatureScreenNames: true);
Instana.setup(key: "<your-instana-key>", reportingURL: "<your-instana-reportingURL>", options: options);
Reference Links