user2411290
user2411290

Reputation: 641

Track the time it takes a user to navigate through an iOS app's UI

I want to measure how long (in seconds) it takes users to do certain things in my app. Some examples are logging in, pressing a button on a certain page, etc.

I am using an NSTimer for that. I am starting it in the viewDidLoad of a specific page, and stopping it at the point that I want to measure.

I also want to measure cumulative time for certain things. I would like to start the timer on the log-in screen, and then continue the timer until the user gets to the next view controller and clicks on a certain button.

I'm not sure how to do this. Should create a global variable in my app delegate? Or is there some other better way?

Upvotes: 1

Views: 52

Answers (1)

picciano
picciano

Reputation: 22701

No need for an NSTimer, you just need to record the start times and compare them to the stop times. Try using a little helper class such as:

class MyTimer {

    static let shared = MyTimer()

    var startTimes = [String : Date]()

    func start(withKey key: String) {
        startTimes[key] = Date()
    }

    func measure(key: String) -> TimeInterval? {
        if let start = startTimes[key] {
            return Date().timeIntervalSince(start)
        }

        return nil
    }

}

To use this, just call start(withKey:) right before you start a long-running task.

    MyTimer.shared.start(withKey: "login")

Do something that takes a while and then call measure(key:) when you're done. Because MyTimer is a singleton, it can be called from anywhere in your code.

    if let interval = MyTimer.shared.measure("login") {
        print("Logging in time: \(interval)")
    }

If you're using multiple threads, you may to to add some thread safety to this, but it should work as is in simple scenarios.

Upvotes: 3

Related Questions