Reputation: 1409
Here's the setup:
I'm building an iOS app that uses a 60 minute timer. Once started I want it to notify the user regardless of the state of the phone (sleeping or viewing my app) to do something when that 60 mins is up.
To do this I have my local notification setup to be executed in my timers method within the appropriate ViewController.m file:
// what happens when the timer ends
if (secondsCount == 0) {
[countdownTimer invalidate];// stops the countdown
countdownTimer = nil;
hourCountDown.text = [NSString stringWithFormat:@"60:00"];// sets the timer to 60 mins
// shows and hides correct UI elements
nowBtn.hidden = YES;
countDown.hidden = YES;
countDown.hidden = YES;
startBtn.hidden = NO;
// shows notification that it's time to do the task
UILocalNotification *itsTime = [[UILocalNotification alloc] init];
itsTime.fireDate = [NSDate dateWithTimeIntervalSinceNow:secondsCount];
itsTime.alertBody = @"Time to do it";
itsTime.timeZone = [NSTimeZone defaultTimeZone];
[[UIApplication sharedApplication] scheduleLocalNotification:itsTime];
itsTime.soundName = UILocalNotificationDefaultSoundName;
// sets the page label
labelState.text = [NSString stringWithFormat:@"Do it!"];
}
In the AppDelegate.m file I have the following code:
- (void)applicationDidEnterBackground:(UIApplication *)application
{ // allows timer to work in background when app isn't up
UIBackgroundTaskIdentifier bgTask =0;
UIApplication *app = [UIApplication sharedApplication];
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
[app endBackgroundTask:bgTask];
}];
}
What I've noticed is it seems to only show the notification when my phone is plugged into my MBP and is running the app via Xcode's simulator. I push the right buttons on my app, wait an hour and the notification is shown. If I unplug the phone, run my app and push the same buttons, wait an hour... no notification is shown.
My question is why? Is this because I'm using the app that was added to my device via the Xcode simulator and not an archive file that I installed like a real app? And if so, what the heck can I do about?
Thanks!
Upvotes: 2
Views: 497
Reputation: 57040
When running in the simulator, background tasks are allowed infinite time. When your phone is connected, you run on the phone. On your phone, the OS gives you a short time to run and when the time ends, your app goes to sleep. On iOS 7, you are given 30 seconds in the background. In iOS 6 and below, 10 minutes. Neither will give you what you want. Either calculate and register the local notification in the future, or use push notifications.
Upvotes: 3