iosswiftuiwindowtouchesbegantouchesended

UIWindow subclass: Touches event not get fired


I want to implement session time feature in my current project. So for that I am trying to subclass UIWindow and override the touchesBegan and touchesEnded methods.

class BaseWindow: UIWindow {

    convenience init() {
        self.init(frame: UIScreen.mainScreen().bounds)
    }

    private var sessionTimeOutTimer: NSTimer?

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        sessionTimeOutTimer?.invalidate()
    }

    override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
        sessionTimeOutTimer = NSTimer.scheduledTimerWithTimeInterval(60, target: CIAppManager.sharedManger(), selector: #selector(CIAppManager.sessionTimeOut), userInfo: nil, repeats: false)
    }
}

In app delegate I did this

private let baseWindow = BaseWindow()
var window: UIWindow? {
    get {
        return baseWindow
    }
    set {}
}

But the problem is touchesBegan and touchesEnded are not get called. I am not able to figure out what's I am doing wrong.


Solution

  • The touchesBegan(_:with:) API will not be called for your window, unless there is no one else to capture the touch event. This is normally never the case, as you want your UI elements to receive touches.

    What you want to implement in your window subclass is sendEvent(:_) and put your logic there. Don't forget to call the super implementation to pass the events.

    A small ceveat with this approach is you will hear some events which are not touch events, but that may not be a problem, as they are mostly user generated anyway.