Search code examples
iosnstimertouchesbegantouches

Auto Signout timer in app?


What I need to do is this; I will have a timer that will tick away and when 30 minutes is up I'll auto signout the user. But if there's any interaction with the application I will reset the timer to 30 min. I have an idea on what to do but I'm sure there's a better way to accomplish this.

What I'll do is make a singleton class that holds a timer and posts a notification when the timer is up. So what I'm thinking is I'll have to reset the timer when ever the user presses a button, goes to the next screen etc.

My quesiton though is is it possible to respond to any touches in the app in one piece of code? Like somehow there's a superclass I can add this to and it will always reset the timer no matter what kind of interaction has happened? Or do I need to add the code to all the places where the user will interact with the application?


Solution

  • You can try this, subclass UIApplication and add following code in implementation

    @implementation MyApplication
    
    - (instancetype)init {
        self = [super init];
        if (self) {
            [self reset];
        }
        return self;
    }
    
    - (void)reset {
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(logout) object:nil];
        [self performSelector:@selector(logout) withObject:nil afterDelay:30*60];
    }
    
    - (void)sendEvent:(UIEvent *)event {
        [super sendEvent:event];
    
        [self reset];
        NSLog(@"event detected");
    }
    
    - (void)logout {
        NSLog(@"logout now");
    }
    @end
    

    Then in main.m change the implementation like this

    return UIApplicationMain(argc, argv, NSStringFromClass([MyApplication class]), NSStringFromClass([AppDelegate class]));
    

    Here what is happening is, - (void)sendEvent:(UIEvent *)event method will get called after each user activity, Then we are registering a perform selector request after 30 mins. Once user touches the screen within 30 mins cancel previous request and register new one.