Добавить локальное уведомление в ios10-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
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
    }
Edit: вам не нужно помещать приложение в фоновом режиме, чтобы представить уведомление от iOS 10 и далее.
используйте ниже обратный вызов, чтобы настроить уведомление для представления на переднем плане.
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
здесь пример проекта.
С Имплемацией Objective-C:
Я написал демо-проект здесь:iOS10AdaptationTips .
- 
импорт UserNotifications ///Notification become independent from Foundation @import UserNotifications;
- 
запрос авторизации для localNotification UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) { if (!error) { NSLog(@"request authorization succeeded!"); [self showAlert]; } }];
- расписание localNotification 
- 
значок приложения обновление номер значка // //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!"); } }];
тогда это будет выглядеть так:
В Фоновом Режиме :
 Экран Блокировки:
 Экран Блокировки:
Если повтор по умолчанию показывает только один 
 вместо того, чтобы показывать много на экране блокировки на iOS9:
 http://i67.tinypic.com/98t75s.jpg
 а также поддержка 3D Touch автоматически
http://a67.tinypic.com/dorw3b.jpg
 
вместо того, чтобы показывать много на экране блокировки на iOS9:
 http://i67.tinypic.com/98t75s.jpg
 а также поддержка 3D Touch автоматически
http://a67.tinypic.com/dorw3b.jpg
Я пишу демо здесь: iOS10AdaptationTips .
Я решил свою проблему следующим образом (Firebase, Swift 3):
найти этот метод на вашем AppDelegate:
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
найти вот эту строку:
completionHandler()
End set:
completionHandler([.alert,.sound,.badge])
уведомления не запускаются, если вы не передаете свои параметры презентации методу completionHandler.
Я сделал реализацию для Swift 3, которая может помочь, вы можете проверить ее здесь:https://stackoverflow.com/a/45381380/2296630
вот несколько шагов:
- убедитесь, что у вас есть разрешение. Если нет, используйте UNUserNotificationCenter.текущий.)(requestAuthorization чтобы сделать это. Или следуйте за ответ если вы хотите показать запрос всплывал не раз. 
- Если вы хотите показать уведомление изображения, имея назначить UNUserNotificationCenterDelegate в где-то. 
- 
Покажите мне код @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]) }
 
            