How To Detect User Inactivity In Swift

Detect user inactivity is important to many apps. Maybe you want to hide something or have the user interface do something after a certain amount of time.

Here’s how I recommend you detect user inactivity in Swift.

How To Detect User Inactivity In Swift

First make a timer property:

var timer: Timer?

Now we’ll create a restartTimer function that we’ll call every time we want to restart the clock:

func resetTimer() {
    timer?.invalidate()
    timer = Timer.scheduledTimer(timeInterval: 10.0, target: self, selector: #selector(hideControls), userInfo: nil, repeats: false)
}

This timer calls a hideControls function after 10 seconds. Let’s create the hideControls function:

@objc func hideControls() {
    // Hide controls here
}

Now call this resetTimer() in viewDidAppear:

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    setupVideoPlayer()
    resetTimer()
}

Now hideControls will called after 10 seconds. But wait! How do we get them back? When the user taps the screen, the controls should re-appear.

To do this we’ll add a gesture recognizer to our whole screen in our viewDidAppear.

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(toggleControls))
view.addGestureRecognizer(tapGesture)

Now we need to create a toggleControls function:

@objc func toggleControls() {
    // toggle controls here
    resetTimer()
}

Now your controls will hide and show every time you tap the screen. The controls will also fade away after 10 seconds of user inactivity.

You can adjust the time interval to your needs.

If you liked this post and want to learn more, check out The Complete iOS Developer Bootcamp. Speed up your learning curve - hundreds of students have already joined. Thanks for reading!

Eddy Chung

I teach iOS development on ZeroToAppStore.com.

Similar Posts