Obtention de notifications locales à afficher lorsque l'application est au premier plan Swift 3

Apparemment, c'est maintenant possible avec ios10:

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

Cette réponse dit essentiellement les outils nécessaires pour le faire:

Afficher une bannière de notification iOS stock lorsque votre application est ouverte et au premier plan?

Je ne comprends pas vraiment comment tout mettre set.

Je ne sais pas à quel point c'est important, mais je ne suis pas capable de garder le func optionnel et xcode veut que je le passe en privé.

J'essaie de montrer le badge, et les docs fournissent

 static var badge: UNNotificationPresentationOptions { get } 

Peu perdu ici.

Et puis je suppose que si je veux exclure un certain controller de vue d'get ces badges et je n'utilise pas un controller de navigation ce code que j'ai trouvé fonctionnerait? : var window: UIWindow?

 if let viewControllers = window?.rootViewController?.childViewControllers { for viewController in viewControllers { if viewController.isKindOfClass(MyViewControllerClass) { print("Found it!!!") } } } 

Il existe une méthode déléguée pour afficher la notification lorsque l'application est ouverte dans iOS 10. Vous devez l'implémenter pour que les notifications riches fonctionnent lorsque l'application est ouverte.

 extension ViewController:UNUserNotificationCenterDelegate { //for displaying notification when app is in foreground func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { //If you don't want to show notification when app is open, do something here else and make a return here. //Even you you don't implement this delegate method, you will not see the notification on the specified controller. So, you have to implement this delegate and make sure the below line execute. ie completionHandler. completionHandler([.alert,.badge]) } // For handling tap and user actions func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { switch response.actionIdentifier { case "action1": print("Action First Tapped") case "action2": print("Action Second Tapped") default: break } completionHandler() } } 

Pour planifier une notification dans iOS 10 et fournir un badge

 override func viewDidLoad() { super.viewDidLoad() // set UNUserNotificationCenter delegate to self UNUserNotificationCenter.current().delegate = self scheduleNotifications() } func scheduleNotifications() { let content = UNMutableNotificationContent() let requestIdentifier = "rajanNotification" content.badge = 1 content.title = "This is a rich notification" content.subtitle = "Hello there, I am Rajan Maheshwari" content.body = "Hello body" content.categoryIdentifier = "actionCategory" content.sound = UNNotificationSound.default() // If you want to attach any image to show in local notification let url = Bundle.main.url(forResource: "notificationImage", withExtension: ".jpg") do { let attachment = try? UNNotificationAttachment(identifier: requestIdentifier, url: url!, options: nil) content.attachments = [attachment!] } let sortinggger = UNTimeIntervalNotificationTrigger.init(timeInterval: 3.0, repeats: false) let request = UNNotificationRequest(identifier: requestIdentifier, content: content, sortinggger: sortinggger) UNUserNotificationCenter.current().add(request) { (error:Error?) in if error != nil { print(error?.localizedDescription) } print("Notification Register Success") } } 

Pour save dans AppDelegate, nous devons écrire ce code dans didFinishLaunchingWithOptions

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. registerForRichNotifications() return true } 

J'ai défini des actions aussi ici. Vous pouvez les ignorer

 func registerForRichNotifications() { UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.badge,.sound]) { (granted:Bool, error:Error?) in if error != nil { print(error?.localizedDescription) } if granted { print("Permission granted") } else { print("Permission not granted") } } //actions defination let action1 = UNNotificationAction(identifier: "action1", title: "Action First", options: [.foreground]) let action2 = UNNotificationAction(identifier: "action2", title: "Action Second", options: [.foreground]) let category = UNNotificationCategory(identifier: "actionCategory", actions: [action1,action2], intentIdentifiers: [], options: []) UNUserNotificationCenter.current().setNotificationCategories([category]) } 

Consultez ce lien pour plus de détails
https://www.youtube.com/watch?v=Svul_gCtzck

Échantillon de Github
https://github.com/kenechilearnscode/UserNotificationsTutorial

Voici la sortie

entrez la description de l'image ici

entrez la description de l'image ici

La key permettant d'afficher vos notifications lorsque votre application est au premier plan est également la suivante:

 content.setValue(true, forKey: "shouldAlwaysAlertWhileAppIsForeground") 

dans votre UNNotificationRequest . Pour le rest, voyez l'excellente réponse de Rajan Maheshwari .

Swift 3 | iOS 10+

En supposant que vous savez comment planifier une notification locale:

 func scheduleLocalNotification(forDate notificationDate: Date) { let calendar = Calendar.init(identifier: .gregorian) let requestId: Ssortingng = "123" let title: Ssortingng = "Notification Title" let body: Ssortingng = "Notification Body" // construct notification content let content = UNMutableNotificationContent() content.title = NSSsortingng.localizedUserNotificationSsortingng(forKey: title, arguments: nil) content.body = NSSsortingng.localizedUserNotificationSsortingng(forKey: body, arguments: nil) content.sound = UNNotificationSound.default() content.badge = 1 content.userInfo = [ "key1": "value1" ] // configure sortinggger let calendarComponents: [Calendar.Component] = [.year, .month, .day, .hour, .minute] let dateComponents = calendar.dateComponents(calendarComponents, from: notificationDate) let sortinggger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false) // create the request let request = UNNotificationRequest.init(identifier: requestId, content: content, sortinggger: sortinggger) // schedule notification UNUserNotificationCenter.current().add(request) { (error: Error?) in if let error = error { // handle error } } } 

Vous devez AppDelegate implémenter le protocole UNUserNotificationCenterDelegate et le définir en tant que délégué du centre de notifications avec UNUserNotificationCenter.current().delegate = self .

 // AppDelegate.swift import UIKit import UserNotifications @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // set app delegate as notification center delegate UNUserNotificationCenter.current().delegate = self } } extension AppDelegate: UNUserNotificationCenterDelegate { // called when user interacts with notification (app not running in foreground) func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { // do something with the notification print(response.notification.request.content.userInfo) // the docs say you should execute this asap return completionHandler() } // called if app is running in foreground func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { // show alert while app is running in foreground return completionHandler(UNNotificationPresentationOptions.alert) } } 

Maintenant, vos notifications locales apparaîtront lorsque votre application sera au premier plan.

Voir les documents UNUserNotificationCenterDelegate pour reference.