0

我进行了很多搜索,试图找到解决这个问题的具体方法。我有一个使用以前的 UILocalNotification 系统发送本地通知的应用程序,这在 iOS 10.3.3 下仍然可以正常工作。但是,我试图将其转换为新的 UNNotification 系统,因为以前的系统已被弃用。无论我尝试使用 UNCalendarNotificationTrigger 还是 UNTimeIntervalNotificationTrigger,代理都不会收到呼叫。这是触发视图控制器的代码。

if (isItTime){
    NSCalendar *currentCalendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
    [currentCalendar setTimeZone:[NSTimeZone localTimeZone]];
    NSDateComponents *components = [currentCalendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond | NSCalendarUnitTimeZone fromDate:[now dateByAddingTimeInterval:30]];
   // components.second = 0;
    NSLog(@"trigger components: %@", components);
    UNCalendarNotificationTrigger* trigger = [UNCalendarNotificationTrigger
                                             triggerWithDateMatchingComponents:components repeats:NO];
    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"invite" content:content trigger:trigger];
    [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
        if (error != nil) {
            NSLog(@"Something went wrong: %@",error);
        }
    }];
    [self.currentLocalNotificationRequests addObject:request];
    return  request;
}else{
    return nil;
}

这是委托(appdelegate)didFinishLaunching 的代码:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
[center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound)
                      completionHandler:^(BOOL granted, NSError * _Nullable error) {
                          // Enable or disable features based on authorization.
                          NSLog(@"_prefix:set($class $method $line)");
                          NSUserDefaults *storage = [NSUserDefaults standardUserDefaults];
                          if(granted == YES){
                              [storage setBool:YES forKey:@"permission granted"];
                              [storage setBool:YES forKey:@"alert permission granted"];
                              [storage setBool:YES forKey:@"sound permission granted"];
                          }else{
                              NSLog(@"No permission granted");
                              [storage setBool:NO forKey:@"permission granted"];
                          };
                      }];

appdelegate 获取通知的代码:

    - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler{
    NSLog(@"appdelegate - center didReceiveNotificationResponse");
    NSString *actionIdentifier = response.actionIdentifier;
    UNNotification *notification = response.notification;
    if([actionIdentifier isEqual:@"com.apple.UNNotificationDefaultActionIdentifier"] || [actionIdentifier isEqual:@"com.apple.UNNotificationDismissActionIdentifier"]){
    }else{

        BOOL accept = [actionIdentifier isEqual:@"ACCEPT_IDENTIFIER"];
        BOOL stop = [actionIdentifier isEqual:@"DECLINE_IDENTIFIER"];
        BOOL doNotDisturb = [actionIdentifier isEqual:@"DO_NOT_DISTURB_IDENTIFIER"];

        if (accept){NSLog(@"accept");
            [self handleAcceptActionWithNotification:notification];
        }
        else if (stop){NSLog(@"stop");
            [self handleDeclineActionWithNotification:notification];
        }
        else if(doNotDisturb) {NSLog(@"do not disturb");
            [self handleDoNotDisturbActionWithNotification:notification];
        };
    }
    completionHandler();
}
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler{
    NSLog(@"appdelegate willPresentNotification");
    UNNotificationRequest * request = notification.request;
    NSString * actionIdentifier = request.identifier;
    if([actionIdentifier isEqualToString:UNNotificationDismissActionIdentifier] || [actionIdentifier isEqualToString:UNNotificationDefaultActionIdentifier]){
    }else{
        if([actionIdentifier isEqualToString:@"invite"]){
            NSLog(@"app delegate notification received while in foreground");
        }
    }
    completionHandler(UNNotificationPresentationOptionAlert + UNNotificationPresentationOptionSound);

}

这是触发代码的NSLog:

<NSDateComponents: 0x146d51c0>
TimeZone: America/Chicago (CDT) offset -18000 (Daylight)
Calendar Year: 2017
Month: 10
Leap month: no
Day: 29
Hour: 14
Minute: 3
Second: 4

很明显,系统没有调用 appdelegate 方法(我确实在通知时间之前将应用程序置于后台,所以应该调用了 didReceiveNotification 方法。

如果有人可以提供帮助,我将不胜感激!

此外,viewDidLoad 中的这段代码:

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(receiveNotificationFromAppDelegate:)
                                                 name:kAppDelegateNotification
                                               object:nil];

    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(applicationBecameActive) name:UIApplicationDidBecomeActiveNotification object:nil];
    self.currentLocalNotificationRequests = [[NSMutableArray alloc]init];
/*
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkDndIndicator) name:UIApplicationDidBecomeActiveNotification object:nil];
 */
    UNNotificationAction *acceptAction = [UNNotificationAction actionWithIdentifier:@"ACCEPT_IDENTIFIER" title:NSLocalizedString(@"Continue notifications", nil) options:UNNotificationActionOptionAuthenticationRequired];
    UNNotificationAction *declineAction = [UNNotificationAction actionWithIdentifier:@"DECLINE_IDENTIFIER" title:NSLocalizedString(@"Stop notifications", nil) options:UNNotificationActionOptionAuthenticationRequired];
    UNNotificationAction *doNotDisturbAction = [UNNotificationAction actionWithIdentifier:@"DO_NOT_DISTURB_IDENTIFIER" title:NSLocalizedString(@"Start Do Not Disturb", nil) options:UNNotificationActionOptionAuthenticationRequired];
    NSArray *actions = [NSArray arrayWithObjects:acceptAction, declineAction, doNotDisturbAction, nil];
    // NSArray *intentIdentifiers = [NSArray arrayWithObjects:@"none", nil];
    UNNotificationCategory *invite = [UNNotificationCategory categoryWithIdentifier:@"com.nelsoncapes.localNotification" actions:actions intentIdentifiers: @[] options:UNNotificationCategoryOptionNone];
    NSSet *categories = [NSSet setWithObjects:invite, nil];
    [center setNotificationCategories:categories];
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound)
                          completionHandler:^(BOOL granted, NSError * _Nullable error) {
                              // Enable or disable features based on authorization.
                              NSLog(@"request granted");
                          }];

以及启动触发过程的代码:

    -(UNNotificationRequest *)startLocalNotification:(NSDate *)fireDate :
(NSMutableDictionary *)userInfo{
    NSUserDefaults *storage = [NSUserDefaults standardUserDefaults];
    UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];
    [center removeAllPendingNotificationRequests];
    UNMutableNotificationContent* content = [[UNMutableNotificationContent alloc] init];
    content.title = NSLocalizedString(@"TimeChime Alert", nil);
    content.body = NSLocalizedString(@"Click to Stop or Change Timer",nil);
    content.categoryIdentifier = @"com.nelsoncapes.localNotification";
4

2 回答 2

0

我没有收到通知,因为我没有指定传递给我的 UNCalendarNotificationTrigger 所需的日期组件。

这不起作用:

NSDateComponents *dateComponents = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour) fromDate:[[NSDate date] dateByAddingTimeInterval:5]];

这有效:

NSDateComponents *dateComponents = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond | NSCalendarUnitNanosecond) fromDate:[[NSDate date] dateByAddingTimeInterval:5]];
于 2021-07-02T07:54:18.877 回答
0

事实证明,这个问题很模糊,但解决起来很容易。不幸的是,我没有仔细遵循编码的第一条规则:RTFD。

Apple 的 UNNotificationRequest> 标识符文档说明:

“如果您在安排新通知时使用相同的标识符,系统会删除先前安排的具有该标识符的通知,并将其替换为新通知。”

我的代码对每个 UNNotificationRequest 使用相同的标识符。尽管每个请求的日历通知日期不同,但系统只保留最近日期的请求。就我而言,触发器会在 1 小时后触发,而我预计它会在 15 分钟后触发。这就是为什么我从未在设备上看到通知以及为什么我从未在委托的 didReceiveNotificationResponse 方法中看到断点的原因。

修复非常简单。只需在以下代码中提供唯一标识符。之后,代码工作。

UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"invite" content:content trigger:trigger];

将 @"invite" 替换为每个请求的唯一标识符。

于 2017-10-31T01:16:50.020 回答