Добавить локальное уведомление в 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

Редактировать:

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


person Bjarte    schedule 14.06.2016    source источник
comment
Вы можете перейти по этой ссылке для подробного использования jayprakashdubey. blogspot.in/2016/07/   -  person Jayprakash Dubey    schedule 31.07.2016
comment
как установить разные компоненты даты или как несколько раз вызывать локальные уведомления?   -  person ArgaPK    schedule 05.03.2018


Ответы (5)


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

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)

Вот пример проекта.

person Anish Parajuli 웃    schedule 14.06.2016
comment
Да, у меня есть это, все еще не повезло. У вас есть полный пример приложения, чтобы я мог увидеть, не пропустил ли я что-нибудь? - person Bjarte; 14.06.2016
comment
@Bjarte в ios10.. мы можем отображать уведомление, когда приложение находится на переднем плане с Android... см. пример проекта.... - person Anish Parajuli 웃; 15.06.2016
comment
привет @anish Я скачал приложение и запустил симулятор. Я не вижу уведомления? - person rOrlig; 16.10.2016
comment
Ах... демо-проект был в бета-версии Xcode 8... Я обновил пример для Xcode 8... - person Anish Parajuli 웃; 07.11.2016
comment
как установить разные компоненты даты или как несколько раз вызывать локальные уведомления? - person ArgaPK; 05.03.2018

С реализацией 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];
                              }
                          }];
    

    Запрос авторизации: введите здесь описание изображения

  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's 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!");
            }
        }];
    

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

В фоновом режиме: введите здесь описание изображения Экран блокировки:
< img src="https://i.stack.imgur.com/bPJsz.jpg" alt="введите здесь описание изображения">

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

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

person ElonChan    schedule 15.06.2016
comment
Привет, я запустил вашу демонстрацию, но она выдает исключение Ошибка утверждения в -[UNTimeIntervalNotificationTrigger _initWithTimeInterval:repeats:] при выполнении UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:5.f Repeats:YES]; . - person Ekta Padaliya; 05.09.2016
comment
Почему вы пишете на Objective-C? - person 4thSpace; 18.09.2016
comment
Потому что он может ;) - person CMash; 28.09.2016
comment
Локальные уведомления не срабатывают... Пожалуйста, проверьте мой пост - person Nazik; 19.10.2016
comment
@EktaPadaliya Завершение работы приложения из-за необработанного исключения «NSInternalInconsistencyException», причина: «при повторении интервал времени должен быть не менее 60» - person ElonChan; 26.10.2016
comment
@ElonChan Привет, Элон, я добавил локальное уведомление, которое вы упомянули здесь, для iOS 10. Я также проверил, что из iOS 10 мы также можем отображать уведомление на переднем плане, но я не могу успешно это реализовать. не могли бы вы помочь мне с этим? - person Nik; 04.11.2016
comment
Привет, я попробовал твою демоверсию. но он не показывает никаких уведомлений. - person Ramakrishna; 14.12.2016

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

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

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

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

completionHandler()

Конечный набор:

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

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

person ibrahimyilmaz    schedule 24.12.2016
comment
Не вижу смысла в огромной структуре, чтобы делать что-то настолько простое. - person Bjarte; 04.01.2017
comment
Apple или Firebase? - person Ryan Pierce; 06.08.2017
comment
Это действительно должно использоваться без фреймворка. Это очень просто сделать - person Liam Bolling; 07.11.2017

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

  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])
    }
    
person Allen    schedule 05.07.2018
comment
Не удается присвоить значение типа «MainScreen» для типа «UNUserNotificationCenterDelegate?», при использовании в представлении загружалась UNUserNotificationCenter.current().delegate = self - person Julian Silvestri; 25.03.2019
comment
Возможно, вы захотите добавить UNUserNotificationCenterDelegate на свой экран (ViewController) - person Allen; 26.03.2019

Я сделал реализацию для Swift 3, которая может помочь, вы можете проверить это здесь: https://stackoverflow.com/a/45381380/2296630

person mourodrigo    schedule 30.07.2017