首页 > 解决方案 > 如何在 localNotification 上安排随机消息

问题描述

如何为 localNotification 安排随机消息。

- (void)viewDidLoad {
        // Do any additional setup after loading the view.
        [super viewDidLoad];
        [self scheduleDailyLocalNotification];
    }


-(void)scheduleDailyLocalNotification{

    UNMutableNotificationContent *localNotification = [UNMutableNotificationContent new];
        localNotification.title = [NSString localizedUserNotificationStringForKey:@“Title!” arguments:nil];
srand(time(NULL));
int r = rand() % 6;
localNotification.body = [NSString localizedUserNotificationStringForKey:[self.notificationMessages objectAtIndex:r] arguments:nil];            
        localNotification.sound = [UNNotificationSound defaultSound];
        UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:60 * 60 * 24  repeats:YES];

        //    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"Time for a run!" content:localNotification trigger:trigger];

        NSString *identifier = @"LOCALNOTIFICATION";
        UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier
                                                                              content:localNotification trigger:trigger];

        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate = self;
        [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
            NSLog(@"NOTIFICATION CREATED");
        }];
 }

它一次又一次地显示相同的信息!

标签: objective-cuilocalnotification

解决方案


如果您不想一次又一次地重复此通知,请设置重复间隔NO

UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:60 * 60 * 24  repeats:NO];

推荐阅读