Repeat local notification every Monday

匿名 (未验证) 提交于 2019-12-03 09:02:45

问题:

I try to repeat a local notification every Monday. I found localNotification.repeatInterval = kCFCalendarUnitWeekOfYear; but I am not sure if it works. How can I show all local notification times in the future?

[[UIApplication sharedApplication] cancelAllLocalNotifications];  NSDate *today = [NSDate date]; NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian]; [gregorian setLocale:[NSLocale currentLocale]];  NSDateComponents *nowComponents = [gregorian components:NSCalendarUnitYear | NSCalendarUnitWeekOfYear | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond fromDate:today];  [nowComponents setHour:18]; [nowComponents setMinute:05]; [nowComponents setSecond:00]; [nowComponents setWeekday:2];  NSDate * notificationDate = [gregorian dateFromComponents:nowComponents];  UILocalNotification* localNotification = [[UILocalNotification alloc] init]; //localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:5]; localNotification.fireDate = notificationDate; localNotification.repeatInterval = kCFCalendarUnitWeekOfYear; localNotification.soundName = @"localNotification_Sound.mp3"; localNotification.alertBody = @"Message?"; localNotification.timeZone = [NSTimeZone defaultTimeZone]; [[UIApplication sharedApplication] scheduleLocalNotification:localNotification]; 

回答1:

I tried out your code in my own simulator and it seems to work just fine.

The only change I would recommend making would be:

localNotification.repeatInterval = NSCalendarUnitWeekOfYear; 

which I found in this very related question.

Also, the compiler will complain if you use lines like:

[nowComponents setMinute:08]; 

(as it interprets that as an octal number instead of an integer). Don't use leading zeros. Do something like:

[nowComponents setMinute:8]; 

Don't forget to ask your user to enable notifications, otherwise they simply won't appear.



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