Подтвердить что ты не робот

Добавить локальное уведомление в iOS 10 - Swift 3

Поэтому я пытался добавить уведомление в новый центр UNUserNotificationCenter, но, похоже, я его не получаю.

У моего контроллера просмотра есть действие:

@IBAction func sendPressed(_ sender: AnyObject) {
    let content = UNMutableNotificationContent()

    content.title = "Hello"
    content.body = "What up?"
    content.sound = UNNotificationSound.default()

    // Deliver the notification in five seconds.
    let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 5, repeats: false)
    let request = UNNotificationRequest.init(identifier: "FiveSecond", content: content, trigger: trigger)

    // Schedule the notification.
    let center = UNUserNotificationCenter.current()
    center.add(request) { (error) in
        print(error)
    }
    print("should have been added")
}

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    let center = UNUserNotificationCenter.current()
    center.requestAuthorization([.alert, .sound]) { (granted, error) in
    }
}

И у меня в проекте тоже есть Notification Content Extension, но, похоже, он вообще не запущен, есть идеи, что мне не хватает? Я пытаюсь привести пример из пользовательской документации, но он ничего не говорит мне, или я пропустил его.

Здесь: https://developer.apple.com/reference/usernotifications/unmutablenotificationcontent

Также: https://developer.apple.com/reference/usernotificationsui https://developer.apple.com/reference/usernotifications

Изменить:

Так что приложение в фоновом режиме сделало свое дело.

4b9b3361

Ответ 1

Вам нужно зарегистрироваться для уведомления... Я пробовал, и это работает.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.
        let center = UNUserNotificationCenter.current()
        center.requestAuthorization([.alert, .sound]) { (granted, error) in
            // Enable or disable features based on authorization.
        }
        return true
    }

Изменить: Вам не нужно размещать свое приложение в фоновом режиме для уведомления с iOS 10 и далее.

Используйте обратный вызов ниже, чтобы настроить уведомление на переднем плане.

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)

Здесь - пример проекта.

Ответ 2

С реализацией Objective-C:

Я написал демо-проект здесь: iOS10AdaptationTips.

  1. импортировать уведомления пользователя

    ///Notification become independent from Foundation
    @import UserNotifications;
    
  2. запросить авторизацию для localNotification

    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert)
                          completionHandler:^(BOOL granted, NSError * _Nullable error) {
                              if (!error) {
                                  NSLog(@"request authorization succeeded!");
                                  [self showAlert];
                              }
                          }];
    

    Запрос авторизации: enter image description here

  3. Расписание локальных уведомлений

  4. обновить номер значка приложения

        //        //Deliver the notification at 08:30 everyday
        //        NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
        //        dateComponents.hour = 8;
        //        dateComponents.minute = 30;
        //        UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:dateComponents repeats:YES];
    
        UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
        content.title = [NSString localizedUserNotificationStringForKey:@"Elon said:" arguments:nil];
        content.body = [NSString localizedUserNotificationStringForKey:@"Hello Tom!Get up, let play with Jerry!"
                                                             arguments:nil];
        content.sound = [UNNotificationSound defaultSound];
    
        /// 4. update application icon badge number
        content.badge = @([[UIApplication sharedApplication] applicationIconBadgeNumber] + 1);
        // Deliver the notification in five seconds.
        UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger
                                                      triggerWithTimeInterval:5.f repeats:NO];
        UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"FiveSecond"
                                                                              content:content trigger:trigger];
        /// 3. schedule localNotification
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
            if (!error) {
                NSLog(@"add NotificationRequest succeeded!");
            }
        }];
    

тогда это будет выглядеть так:

На заднем плане: enter image description here  Экран блокировки:
enter image description here

Если повтор по умолчанию показывает только один enter image description here вместо того, чтобы показывать много на экране блокировки на iOS9:   enter image description here  а также поддержка 3D Touch автоматически enter image description here

Я пишу демо здесь: iOS10AdaptationTips.

Ответ 3

Вот несколько шагов:

  1. Убедитесь, что у вас есть разрешение. Если нет, используйте UNUserNotificationCenter.current(). RequestAuthorization, чтобы получить это. Или выполните ответ, если вы хотите показать, что запрос появляется несколько раз.

  2. Если вы хотите, чтобы показать на переднем плане уведомления, необходимости привязывать UNUserNotificationCenterDelegate куда - то.

  3. Покажите мне код

    @IBAction func sendPressed(_ sender: AnyObject) {
        let content = UNMutableNotificationContent()
        content.title = "Hello"
        content.body = "What up?"
        content.sound = UNNotificationSound.default()
    
        let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 5, repeats: false)
        let request = UNNotificationRequest.init(identifier: "FiveSecond", content: content, trigger: trigger)
    
        let center = UNUserNotificationCenter.current()
        center.add(request) { (error) in
            print(error)
        }
    }
    
    override func viewDidLoad(_ animated: Bool) {
        super.viewDidLoad(animated)
    
        // Assign the delegate
        UNUserNotificationCenter.current().delegate = self
    
        // Ask the permission
        let center = UNUserNotificationCenter.current()
        center.requestAuthorization([.alert, .sound]) { (granted, error) in
            if granted {
                // do something
            }
        }
    }
    // Remember to add UNUserNotificationCenterDelegate to your view controller
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        print("Got the msg...")
        completionHandler([.badge, .sound, .alert])
    }
    

Ответ 4

Я решил свою проблему следующим образом (Firebase, Swift 3):

Найти этот метод в AppDelegate:

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

Найти эту строку:

completionHandler()

Конечное множество:

completionHandler([.alert,.sound,.badge])

уведомления не запускаются, если вы не передадите свои параметры презентации методу завершенияHandler.

Ответ 5

Я сделал реализацию для Swift 3, которая может помочь, вы можете проверить ее здесь: fooobar.com/info/229793/...