【发布时间】:2020-01-09 06:54:55
【问题描述】:
我希望我的应用在每天早上 7 点和晚上 7 点发送本地通知。怎么做?请帮忙
我需要每天发送两个本地通知,一个在早上 7 点,另一个在晚上 7 点。
{ - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
if (![[NSUserDefaults standardUserDefaults] boolForKey:@"HasLaunchedOnce"])
{
static dispatch_once_t once;
dispatch_once(&once, ^ {
NSLog(@"Do it once");
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar] ;
NSDate *now = [NSDate date];
NSDateComponents *components = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:now];
[components setHour:13];
[components setMinute:1];
UILocalNotification *notification = [[UILocalNotification alloc]init];
notification.fireDate = [calendar dateFromComponents:components];
notification.repeatInterval = kCFCalendarUnitDay;
[notification setAlertBody:@"AM U got notification!!!"];
// notification.soundName = UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
[components setHour:17];
[components setMinute:28];
notification.fireDate = [calendar dateFromComponents:components];
notification.repeatInterval = NSCalendarUnitDay;
[notification setAlertBody:@"PM U got notification!!!"];
// notification.soundName = UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
});
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"HasLaunchedOnce"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
我已经编写了 if 条件,以便在安装应用程序后只运行一次代码,否则每次打开应用程序时都会设置本地通知。现在在同一天它工作正常,但在第二天它不会重复。请帮忙。或者有没有其他方法可以在每天早上 7 点和晚上 7 点获得本地通知?
【问题讨论】:
标签: objective-c ios12 xcode10.2