iPhone: Detecting user inactivity/idle time since last screen touch

前端 未结 9 1279
我寻月下人不归
我寻月下人不归 2020-11-22 17:10

Has anybody implemented a feature where if the user has not touched the screen for a certain time period, you take a certain action? I\'m trying to figure out the best way t

9条回答
  •  花落未央
    2020-11-22 17:33

    For swift v 3.1

    dont't forget comment this line in AppDelegate //@UIApplicationMain

    extension NSNotification.Name {
       public static let TimeOutUserInteraction: NSNotification.Name = NSNotification.Name(rawValue: "TimeOutUserInteraction")
    }
    
    
    class InterractionUIApplication: UIApplication {
    
    static let ApplicationDidTimoutNotification = "AppTimout"
    
    // The timeout in seconds for when to fire the idle timer.
    let timeoutInSeconds: TimeInterval = 15 * 60
    
    var idleTimer: Timer?
    
    // Listen for any touch. If the screen receives a touch, the timer is reset.
    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()
                }
            }
        }
    }
    
    // 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(self.idleTimerExceeded), userInfo: nil, repeats: false)
    }
    
    // If the timer reaches the limit as defined in timeoutInSeconds, post this notification.
    func idleTimerExceeded() {
        NotificationCenter.default.post(name:Notification.Name.TimeOutUserInteraction, object: nil)
       }
    } 
    

    create main.swif file and add this (name is important)

    CommandLine.unsafeArgv.withMemoryRebound(to: UnsafeMutablePointer.self, capacity: Int(CommandLine.argc)) {argv in
    _ = UIApplicationMain(CommandLine.argc, argv, NSStringFromClass(InterractionUIApplication.self), NSStringFromClass(AppDelegate.self))
    }
    

    Observing notification in an any other class

    NotificationCenter.default.addObserver(self, selector: #selector(someFuncitonName), name: Notification.Name.TimeOutUserInteraction, object: nil)
    

提交回复
热议问题