xcode - 随时间安排的本地通知(每天早上 6 点)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10266336/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 00:02:33  来源:igfitidea点击:

xcode - scheduled local notification with time ( Everyday at 6AM )

iphoneobjective-cxcodeuilocalnotification

提问by shebi

I'm using Xcode 4.3.2, How can i set this local notification "dateToFire" everyday at 6AM?

我正在使用 Xcode 4.3.2,如何在每天早上 6 点设置此本地通知“dateToFire”?

-(void)notification
{
    UILocalNotification *localNotification = [[[UILocalNotification alloc] init] autorelease];

    if (!localNotification) 
        return;

    // Current date
    NSDate *date = [NSDate date]; 
    NSDate *dateToFire = //Everyday: 6AM;

    // Set the fire date/time
    [localNotification setFireDate:dateToFire];
    [localNotification setTimeZone:[NSTimeZone defaultTimeZone]];
    [localNotification setAlertBody:@"Notification" ];      

    [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self notification];
}

回答by Nikita Pestrov

Use CalendarComponentsto set the hour to 6, and set localNotification.repeatIntervalto NSDayCalendarUnit

使用CalendarComponents将小时设置为 6,并将localNotification.repeatInterval设置为 NSDayCalendarUnit

NSCalendar *calendar = [NSCalendar currentCalendar]; // gets default calendar
NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:[NSDate date]]; // gets the year, month, day,hour and minutesfor today's date
[components setHour:18];
[components setMinute:0];

localNotification.fireDate = [calendar dateFromComponents:components];