Уведомления пользователей с использованием UNUserNotificationCenter с настройкой оповещений в системных настройках

#macos #cocoa

#macos #cocoa

Вопрос:

Я использую macOS Mojave и перешел с использования NSUserNotification, который теперь устарел, на UNUserNotificationCenter. Мое приложение отображается в уведомлениях системных настроек с выбранным стилем баннера. Всегда ли стиль баннера используется по умолчанию? Я действительно хочу начать со стиля оповещений, чтобы пользователь мог видеть доступные кнопки.

     // 03-27-2019 commented. has absolutely no effect on the notification appearing
    UNAuthorizationOptions options = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge | UNAuthorizationOptionProvidesAppNotificationSettings;
    [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:options

  
 UNNotificationAction* snoozeAction = [UNNotificationAction
                                      actionWithIdentifier:@"SNOOZE_ACTION"
                                      title:@"Snooze"
                                      options:UNNotificationActionOptionNone];  // 03-25-2019 The action has the default behavior.

UNNotificationAction* stopAction = [UNNotificationAction
                                    actionWithIdentifier:@"STOP_ACTION"
                                    title:@"Stop"
                                    options:UNNotificationActionOptionForeground];  // 03-25-2019 The action causes the app to launch in the foreground.

// start 03-27-2019
UNNotificationAction* bogusAction = [UNNotificationAction
                                     actionWithIdentifier:@"BOGUS_ACTION"
                                     title:@"Bogus"
                                     options:UNNotificationActionOptionForeground];  // 03-25-2019 The action causes the app to launch in the foreground.

                                                                    completionHandler:^(BOOL granted, NSError * _Nullable error) {
                                                                        if (!granted) {
                                                                            NSLog(@"requestAuthorizationWithOptions: NO");
                                                                        } else {
                                                                            NSLog(@"requestAuthorizationWithOptions: YES");
                                                                       }
  
 UNNotificationCategory* expiredCategoryPlus = [UNNotificationCategory
                                               categoryWithIdentifier:@"TIMER_EXPIRED_PLUS"
                                                   actions:@[snoozeAction, stopAction, bogusAction]   // 03-27-2019 show just 1 button with "Actions": snooze, stop, bogus

UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];

[center setNotificationCategories:[NSSet setWithObjects:expiredCategoryPlus, // 03-28-2019

// display the notification
UNMutableNotificationContent* content = [[UNMutableNotificationContent alloc] init];
content.title = [NSString localizedUserNotificationStringForKey:@"Wake up!" arguments:nil];
content.subtitle = [NSString localizedUserNotificationStringForKey:@"The subtitle." arguments:nil];
content.body = [NSString localizedUserNotificationStringForKey:@"Rise and shine! It's morning time!"
                                                         arguments:nil];
content.sound = [UNNotificationSound defaultSound];
content.attachments = @[]; 
content.categoryIdentifier = @"TIMER_EXPIRED_PLUS";

    // configure trigger for right now
    NSDate *now = [NSDate date];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    [calendar setTimeZone:[NSTimeZone localTimeZone]];
    NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond | NSCalendarUnitTimeZone fromDate:now];

    // set the trigger
    UNCalendarNotificationTrigger* trigger = [UNCalendarNotificationTrigger
                                              //                                              triggerWithDateMatchingComponents:date repeats:NO];
                                              triggerWithDateMatchingComponents:components repeats:NO];

    // Create the request object.
    UNNotificationRequest* request = [UNNotificationRequest
                                      requestWithIdentifier:@"MorningAlarm" content:content trigger:trigger];

    // Schedule the notification.
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    //        [center addNotificationRequest:request];  // 02-23-2019 don't compile
    [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
        if (!error) {
            NSLog(@"Local Notification succeeded");
        }
        else {
            NSLog(@"Local Notification failed");
        }
    }];

  

Ответ №1:

Обратился в службу поддержки разработчиков Apple, и я не делаю ничего плохого. Apple разработала уведомления в виде баннеров, хотя я запрашиваю оповещения с параметрами несанкционированного доступа. Итак, теперь я знаю.