Posted in

Easiest way to add page events globally with method swizzling

method swizzling

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!

I'm a passionate iOS Developer with over 10 years of experience building high-quality iOS apps using Objective-C, Swift, and SwiftUI. I created iostutor.com to share practical tips, tutorials, and insights for developers of all levels.

When I’m not coding, I enjoy exploring new technologies and writing content — from technical guides to stories and poems — with the hope that it might help or inspire someone, somewhere.

Leave a Reply

Your email address will not be published. Required fields are marked *