iOS perform action after period of inactivity (no user interaction)

前端 未结 6 1998
慢半拍i
慢半拍i 2020-11-28 01:46

How can I add a timer to my iOS app that is based on user interaction (or lack thereof)? In other words, if there is no user interaction for 2 minutes, I want to have the ap

6条回答
  •  清酒与你
    2020-11-28 01:49

    Swift 3.0 Conversion of the subclassed UIApplication in Vanessa's Answer

    class TimerUIApplication: UIApplication {
    static let ApplicationDidTimoutNotification = "AppTimout"
    
        // The timeout in seconds for when to fire the idle timer.
        let timeoutInSeconds: TimeInterval = 5 * 60
    
        var idleTimer: Timer?
    
        // Resent the timer because there was user interaction.
        func resetIdleTimer() {
            if let idleTimer = idleTimer {
                idleTimer.invalidate()
            }
    
            idleTimer = Timer.scheduledTimer(timeInterval: timeoutInSeconds, target: self, selector: #selector(TimerUIApplication.idleTimerExceeded), userInfo: nil, repeats: false)
        }
    
        // If the timer reaches the limit as defined in timeoutInSeconds, post this notification.
        func idleTimerExceeded() {
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: TimerUIApplication.ApplicationDidTimoutNotification), object: nil)
        }
    
    
        override func sendEvent(_ event: UIEvent) {
    
            super.sendEvent(event)
    
            if idleTimer != nil {
                self.resetIdleTimer()
            }
    
            if let touches = event.allTouches {
                for touch in touches {
                    if touch.phase == UITouchPhase.began {
                        self.resetIdleTimer()
                    }
                }
            }
    
        }
    }
    

提交回复
热议问题