如何知道我们的应用程序是活动还是空闲?

时间:2017-11-14 05:20:24

标签: ios swift timer timeout user-interaction

我希望在" x"之后在我的应用程序中设置自动超时场景分钟。我尝试使用计划计时器进行计时器调用(在" x" mins之后)。用户正在阅读具有可滚动/轻敲状态的T& C页面,同时触发计时器。但是当用户没有做任何动作(触摸,滚动)时,我期待定时器调用。如果用户在指定的时间段内没有触摸屏幕,我需要调用超时弹出窗口。我想为整个应用程序处理这个超时场景。

1 个答案:

答案 0 :(得分:3)

您可以在UIWindow上使用UIGestureRecognizerDelegate来接收屏幕上的内容。 在这个timeOut函数将调用后,我在这里添加了5秒的计时器。

Appdelegate

中添加 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") }
func addUIButton(){
        //next button 
        let myButton = UIButton()
        myButton.setTitle("Next", for: UIControlState.normal)
        myButton.setTitleColor(UIColor.red, for: .normal)
        myButton.frame = CGRect(x: self.view.frame.size.width - 50, y: self.view.frame.size.height/2 - 50, width: 50, height: 50)
        myButton.addTarget(self, action: #selector(pagesViewController.pressed(sender:)), for: .touchUpInside)
        self.view.addSubview(myButton)
        self.view.bringSubview(toFront: myButton)
    }
    func addSecondUIButton(){
        //previous button
        let myButton = UIButton()
        myButton.setTitle("Previous", for: UIControlState.normal)
        myButton.setTitleColor(UIColor.red, for: .normal)
        myButton.frame = CGRect(x: 20, y: self.view.frame.size.height/2 - 50, width: 100, height: 50)
        myButton.addTarget(self, action: #selector(pagesViewController.Secondpressed(sender:)), for: .touchUpInside)
        self.view.addSubview(myButton)
        self.view.bringSubview(toFront: myButton)
    }