Question

I have an application that has a loginVC, when the user is logged in I want that after 12 hours the application invokes the method -(void)logout, using these lines [self performSelector:@selector(logout) withObject:nil afterDelay:43200];, in the viewDidLoad method of the UserLoggedVC. if the application is open or in background with a short time parameter in afterDelay, like 600 secs (10 minutes), the method is called fine, but when is a long time like 43200 secs(12 hours), and the application is in background the method is never called.

I hope you can help me

Was it helpful?

Solution 2

The answers from Gabriele and tdevoy clearly states why it is not possible. So I'm not repeating the same thing, instead if you cant find out how to do it, this is how you can try:

In your viewDidLoad, store the logged in time in NSUserDefaults like this

NSDate *currentDate= [NSDate date];
[[NSUserDefaults standardUserDefaults] setObject:currentDate forKey:@"loggedInTime"];

Now in your applicationDidBecomeActive delegate method,

NSDate *loggedInTime = (NSDate *)[[NSUserDefaults standardUserDefaults] objectForKey:@"loggedInTime"];
NSTimeInterval timeSpentInApp = [[NSDate date] timeIntervalSinceDate:loggedInTime];
//if this timeSpentInApp is greater than 43200, then you can call logout. 
//(Make sure after relogin, the loggedInTime value was updated again.)

But, if the user continuously uses the app for 12 hrs, then you should consider using your code snippet too, as this will call only when the app comes from background.

OTHER TIPS

performSelector: withObject: afterDelay: is essentially just a timer and timers are not allowed in the background.

Instead you should just record the timestamp when the user first logs in to the application and save it. Then each time the application comes to the foreground just check to see if its been 12 hours from the current time to the log in time.

You cannot expect your application to be alive in memory for 12 hours. When the application goes in background the OS will eventually kill it, so your method will never execute.

The approach here can be either to store the date of the last user activity and check it against the current one when the user opens the app, or to perform the check server side and force the logout.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top