My app runs constantly in kiosk mode. Once every 24 hours at a specific time I need to sync some data from core data to a web service.
I know how to do the sync piece but I don't know how to schedule the app to make the sync call at a specific time each day e.g. at 02:45 am.
Is it possible to do something like this when an app is running constantly?
Use Local Notifications. Here is a tutorial:http://www.icodeblog.com/2010/07/29/iphone-programming-tutorial-local-notifications/
Hope this helps u to start...
This as well:
Local Notifications
Background Tasks
Figured this out thanks to prompts from @lakesh. Posting solution in the case it helps somebody because I found NSNotification examples very difficult to understand at first.
In my main view controller I added the following method:
- (void)scheduleNotification
{
[[UIApplication sharedApplication] cancelAllLocalNotifications];
UILocalNotification *notif = [[UILocalNotification alloc] init];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:[NSDate date]];
NSInteger day = [components day];
NSInteger month = [components month];
NSInteger year = [components year];
[components setDay: day];
[components setMonth: month];
[components setYear: year];
[components setHour: 02];
[components setMinute: 45];
[components setSecond: 0];
[calendar setTimeZone: [NSTimeZone systemTimeZone]];
NSDate *dateToFire = [calendar dateFromComponents:components];
notif.fireDate = dateToFire;
notif.timeZone = [NSTimeZone systemTimeZone];
notif.repeatInterval = NSDayCalendarUnit;
[[UIApplication sharedApplication] scheduleLocalNotification:notif];
}
This sets a fire date for the notification of today at 02:45 am and recurs daily.
In viewDidLoad in my view controller I call the above method:
[self scheduleNotification];
In the appdelegate I do the following:
- (void)application:(UIApplication *)application didReceiveLocalNotification: (UILocalNotification *)notification
{
application.applicationIconBadgeNumber = 0;
//call your method that you want to do something in your app
}
A simple solution is just to set NSTimer
to check current date every minute (or every second, for example). If the current date is greater then required, then fire the method and update the required date.