ios - 如何知道您的应用程序是事件的还是空闲的?

标签 ios swift timer timeout user-interaction

我想在“x”分钟后在我的应用程序中设置自动超时场景。我尝试使用计划定时器调用定时器(“x”分钟后)。用户正在阅读具有可滚动/点击状态的 T&C 页面,同时触发了计时器。但是当用户不执行任何操作(触摸、滚动)时,我期待计时器调用。简单地说,如果用户在指定的时间段内没有触摸屏幕,我需要调用超时弹出窗口。我想为我的整个应用程序处理这种超时情况。

最佳答案

您可以在接收屏幕触摸的 UIWindow 上使用 UITapGestureRecognizer。 在这里,我添加了 5 秒的计时器,超时函数将调用。

Appdelegate中添加UIGestureRecognizerDelegate

   var window: UIWindow?
    var timer: Timer?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        let tapGesture = UITapGestureRecognizer(target: self, action: nil)
        tapGesture.delegate = self
        window?.addGestureRecognizer(tapGesture)
       //Start timer for first time
        timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(self.timeOut), userInfo: nil, repeats: false)
        return true
    }

    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        print(" tapped on screen,")
        timer?.invalidate()
        //set Timer Ex: 5 Second
        //Run timer on touch
        timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(self.update), userInfo: nil, repeats: false)
        return false
    }
    @objc func timeOut() {
        print("TimeOut")
    }

关于ios - 如何知道您的应用程序是事件的还是空闲的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47278193/

相关文章:

ios - Xcode8 Controller 是灰色的,它们是在 Xcode 7 中设计的,具有尺寸等级

ios - Xcode:删除对未显示为选项的文件的引用

swift - 准备函数不通过segue调用

c - 内核模块计时器杀死系统

C# 为什么定时器频率非常低?

ios - 具有多个属性的 NSMutableArray

objective-c - iOS 在旋转时重新组织图形

ios - 将平板电脑布局添加到iOS手机布局

ios - 从 VC1 向 VC2 传递值

android - 继续查询时间直到匹配给定时间