How to detect user inactivity for 5 seconds in iOS?


While designing any iOS Application you might come across a scenario where you have to do some sort of action if the screen is inactive for some amount of time.

Here we will be seeing the same, we will be detecting user inactivity for 5 seconds.

We will be using Apple’s UITapGestureRecognizer you can read more about it here

https://developer.apple.com/documentation/uikit/uitapgesturerecognizer.

So Let’s get started! We will be designing a basic application where we will start the timer as soon as the application is launched. If the user fails to touch the screen or does not perform any operation till 5 seconds we will be displaying a message “User inactive for more than 5 seconds .” If the user touch the screen we will reset the timer.

Step 1 − Open Xcode -→ Single View Application -→ Let’s name is “DetectingInactivity”.

Step 2 − Open ViewController.swift and copy and add the code, we will be seeing the explanation below

import UIKit
class ViewController: UIViewController {
   // create object of timer class
   var timer = Timer()
   override func viewDidLoad() {
      super.viewDidLoad()
      timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(ViewController.doStuff), userInfo: nil, repeats: true)
      let resetTimer = UITapGestureRecognizer(target: self, action: #selector(ViewController.resetTimer));
      self.view.isUserInteractionEnabled = true
      self.view.addGestureRecognizer(resetTimer)
   }
   @objc func doStuff() {
      // perform any action you wish to
      print("User inactive for more than 5 seconds .")
      timer.invalidate()
   }
   @objc func resetTimer() {
      timer.invalidate()
      timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(ViewController.doStuff), userInfo: nil, repeats: true)
   }
}

Step 3 − Run the application!

On launch the timer gets called and if you do not touch the screen function doStuff() gets called. Here you can perform any activity which you wish to whenever the user do not touch the screen for certain amount of time.

If the user touches the screen we call resetTimer() function where we reset the timer again.

Updated on: 30-Jul-2019

847 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements