Calling A Method At Specific Time Every Day

馋奶兔 提交于 2019-11-27 23:21:04

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!