Writing an Idle Timer in Swift

Felipe Ricieri
2 min readDec 22, 2022

Invalidating a session after a certain period of time.

Sometimes we don't want the user to have unlimited access to information, at least during a continuous period of time (what we often reference as a "session"). For such, being able to invalidate this access privilege is valuable.

Today we'll build an Idle Timer — a mechanism that will be triggered by user interactions in an app to renew the session timeout. There's a fairly simple approach to take, which has zero cost to scale.

I like to do it by intercepting the events that are being delivered to the Application. We'll trigger a timer whenever an event happens and then invalidate & restart it in the next event. If the timeout we have set is smaller than the time interval the app needed to wait for the next event, then we can consider terminating the session.

There's no secret here, we'll have to extend the Application class and override the sendEvent method to intercept these events.

Taking a step back, did you ever wonder what is an AppDelegate? There is a class sitting…

--

--