Sometimes interviewer may ask What is the easiest way to add page events in all classes of existing project ? or in other words What is Method Swizzling ?
Yes, Method Swizzling is the right way to add events in such situations.
To add page events (like analytics or logging) to all view controllers in your existing iOS project, the easiest and most maintainable way is to use method swizzling on UIViewController’s lifecycle methods — typically viewDidAppear.
Problem: You want to log or send an event every time a screen (UIViewController) appears — without manually adding code to each class.
Solution: Method Swizzling of viewDidAppear
1. Create a UIViewController Extension
import UIKit
import ObjectiveC
extension UIViewController {
// This method will replace the original viewDidAppear
@objc func swizzled_viewDidAppear(_ animated: Bool) {
// Call the original implementation (now swizzled)
self.swizzled_viewDidAppear(animated)
// Send analytics
AnalyticsManager.shared.trackScreen(name: String(describing: type(of: self)))
}
// Call this once, typically in AppDelegate or once in your project
static func swizzleViewDidAppear() {
// Ensure it's only swizzled once
guard self === UIViewController.self else { return }
let originalSelector = #selector(viewDidAppear(_:))
let swizzledSelector = #selector(swizzled_viewDidAppear(_:))
guard
let originalMethod = class_getInstanceMethod(self, originalSelector),
let swizzledMethod = class_getInstanceMethod(self, swizzledSelector)
else {
return
}
// Exchange implementations
method_exchangeImplementations(originalMethod, swizzledMethod)
}
}
2. Activate Swizzling in AppDelegate
In your AppDelegate.swift (or SceneDelegate.swift for modern projects), add:
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UIViewController.swizzleViewDidAppear()
return true
}
Now, every viewDidAppear(_:)
in your app will trigger the analytics event automatically — without changing any view controller code!
What This Gives You
- Automatically logs every screen appearance across your app.
- No need to manually insert logging into each view controller.
- Keeps code centralized and maintainable.
⚠️ Caution note:
- Use swizzling only for safe methods like viewDidAppear.
- Avoid swizzling in production code without full testing, especially if you rely on third-party SDKs that may also swizzle the same method.
Alternative (if you want something safer)
If you prefer not to use swizzling, you could:
- Create a BaseViewController and subclass all your view controllers from it.
- Override viewDidAppear in the base class to log the event.
- But this requires a small amount of refactoring in each class.
Thank you, fellow developers!