如何在 iOS 中检测用户 5 秒的无活动状态?
iosapps/applicationsmobile development更新于 2026/2/15 14:07:17
在设计任何 iOS 应用程序时,您可能会遇到这样的情况:如果屏幕在一段时间内处于无活动状态,您需要执行某种操作。
这里我们将看到相同的情况,我们将检测用户 5 秒的无活动状态。
我们将使用 Apple 的 UITapGestureRecognizer,您可以在此处了解更多信息
https://developer.apple.com/documentation/uikit/uitapgesturerecognizer.
那么,让我们开始吧!我们将设计一个基本的应用程序,并在应用程序启动后立即启动计时器。如果用户未触摸屏幕或 5 秒内未执行任何操作,我们将显示一条消息"用户未活动超过 5 秒"。如果用户触摸屏幕,我们将重置计时器。
步骤 1 − 打开 Xcode --> 单视图应用程序 --> 我们将其命名为"DetectingInactivity"。
步骤 2 − 打开 ViewController.swift 并复制并添加代码,我们将在下方看到相关解释
import UIKit
class ViewController: UIViewController {
// 创建计时器类的对象
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() {
// 执行您想要的任何操作
print("用户处于非活动状态超过 5 秒。")
timer.invalidate()
}
@objc func resetTimer() {
timer.invalidate()
timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(ViewController.doStuff), userInfo: nil, repeats: true)
}
}
步骤 3 −运行应用程序!
启动时,计时器会被调用;如果您没有触摸屏幕,则会调用 doStuff() 函数。在这里,只要用户在一定时间内没有触摸屏幕,您就可以执行任何您想要的操作。
如果用户触摸屏幕,我们会调用 resetTimer() 函数,再次重置计时器。

