首页 > 解决方案 > 如何每天在两个不同的时间获得本地通知?

问题描述

我希望我的应用程序在每天早上 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-cios12xcode10.2

解决方案


本地通知没有重复。无论您希望安排多少天,您都必须安排多个通知。


推荐阅读