Уведомления пользователей с помощью UNUserNotificationCenter с настройкой оповещений в системных настройках - PullRequest
0 голосов
/ 02 апреля 2019

Я использую 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 Ответ

0 голосов
/ 04 апреля 2019

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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...