且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

iPhone:每日本地通知

更新时间:2023-02-26 21:05:25

您只需要正确创建一个 NSDate 对象是您的开火日期(时间)。而不是使用 [NSDate dateByAddingTimeInterval:20] ,请使用以下内容:

You just need to properly create a NSDate object to be your fire date (time). Instead of using [NSDate dateByAddingTimeInterval: 20], use something like this:

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay: 3];
[components setMonth: 7];
[components setYear: 2012];
[components setHour: 6];
[components setMinute: 0];
[components setSecond: 0];
[calendar setTimeZone: [NSTimeZone defaultTimeZone]];
NSDate *dateToFire = [calendar dateFromComponents:components];

这是Apple NSDateComponents API文档

然后当你添加通知日期,将重复间隔设置为一天:

And then when you add the date to the notification, set the repeat interval to one day:

[localNotification setFireDate: dateToFire];
[localNotification setTimeZone: [NSTimeZone defaultTimeZone]];
[localNotification setRepeatInterval: kCFCalendarUnitDay];

与所有与日期相关的代码一样,请确保在切换到夏令时期间测试其工作原理,如果您的时区使用夏令时。

As with all date related code, make sure to test how this works during the switch to daylight savings time, if your time zone uses daylight savings time.