ios-使用NSTimeInterval变量时不会触发UNTimeIntervalNotificationTrigger,而是使用常量触发

时间:2019-01-05 15:56:46

标签: ios notifications

我遇到了一个奇怪的问题:UNTimeIntervalNotificationTrigger triggerWithTimeInterval:repeats:由诸如10之类的常数触发,但没有由NSTimeInterval variable触发。

ios 12.1.2。

在以下代码中,如果我在

中使用计算出的interval

UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:interval repeats:NO];

通知未触发。

如果我使用常量,则触发通知:

UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:10 repeats:NO];

这是代码段。

- (void)addLocalNotificationForNewVersionWithSubject:(NSString *)subject
                                                body:(NSString *)body
                                          sendAtTime:(NSDate *)sendAtTime API_AVAILABLE(ios(10)) {
    UNMutableNotificationContent *content = [UNMutableNotificationContent new];
    content.title = subject;
    content.body = body;
    content.sound = [UNNotificationSound defaultSound];

    // timeIntervalSinceDate returns negative value for future date, positive value for past date. but UNTimeIntervalNotificationTrigger needs positive value for future date. this is what (0 - timeIntervalSinceDate) means.
    // UNTimeIntervalNotificationTrigger throws exception if interval parameter is not greater than 0. so for negative value for past date, i send the notificaion 10 seconds in the future.
    NSTimeInterval interval = (0 - [[NSDate date] timeIntervalSinceDate:sendAtTime]);
    if (interval <= 0) {
        interval = 10;
    }
    // here is the difference.
    UNTimeIntervalNotificationTrigger *trigger =
        [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:interval repeats:NO];

    UNNotificationRequest *request = [UNNotificationRequest
        requestWithIdentifier:@“some_identifier" content:content trigger:trigger];
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate = self;
    [center addNotificationRequest:request withCompletionHandler:^(NSError *_Nullable error) {
        if (error) {
            NSLog(@“add notification failure:%@", error);
            return;
        }
        NSLog(@"add notification successful, %@", request);
    }];
}

有人知道吗?

谢谢!

0 个答案:

没有答案