Anteriormente usé el siguiente código para diferenciar si mi notificación es local o remota cuando se inicia la aplicación
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { if (launchOptions?[UIApplication.LaunchOptionsKey.localNotification] != nil) { } if (launchOptions?[UIApplication.LaunchOptionsKey.remoteNotification] != nil) { } }Las condiciones son que mi aplicación se elimine y la estoy abriendo desde la notificación.
El problema es que este método
if (launchOptions?[UIApplication.LaunchOptionsKey.localNotification] != nil) { }está en desuso y no se llama al siguiente método cuando la aplicación se abre desde el centro de notificaciones
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {}Puede comprobar el tipo de notificación en userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler: también,
La jerarquía de clases es:
UNNotificationResponse>UNNotification>UNNotificationRequest>UNNotificationTrigger
Hay 4 tipos de disparadores en UNNotificationRequest :
UNLocationNotificationTriggerUNPushNotificationTriggerUNTimeIntervalNotificationTriggerUNCalendarNotificationTriggerSolo usa,
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { if response.notification.request.trigger is UNPushNotificationTrigger { print("remote notification"); } }Al crear una notificación local, establezca el identificador en la notificación que se puede usar para identificar la diferencia en el manejo de la notificación.
El siguiente es un ejemplo de cómo crear una notificación local con un identificador.
let content = UNMutableNotificationContent() content.title = "Title" content.body = "Body" content.sound = UNNotificationSound.default() let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false) let request = UNNotificationRequest(identifier: "TestIdentifier", content: content, trigger: trigger) UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)Manejo de notificación local con identificador.
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { if response.notification.request.identifier == "TestIdentifier" { print("handling notifications with the TestIdentifier Identifier") } completionHandler() }Para el manejo de notificaciones remotas, puede usar la siguiente línea
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { print("handling notification") if let notification = response.notification.request.content.userInfo as? [String:AnyObject] { let message = parseRemoteNotification(notification: notification) print(message as Any) } completionHandler() } private func parseRemoteNotification(notification:[String:AnyObject]) -> String? { if let aps = notification["aps"] as? [String:AnyObject] { let alert = aps["alert"] as? String return alert } return nil }Puede agregar una condición adicional para manejar ambas notificaciones en el mismo método al verificar el identificador en la primera línea.
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { print("handling notification") if response.notification.request.identifier == "TestIdentifier" { print("handling notifications with the TestIdentifier Identifier") }else { if let notification = response.notification.request.content.userInfo as? [String:AnyObject] { let message = parseRemoteNotification(notification: notification) print(message as Any) } } completionHandler() } private func parseRemoteNotification(notification:[String:AnyObject]) -> String? { if let aps = notification["aps"] as? [String:AnyObject] { let alert = aps["alert"] as? String return alert } return nil }Puede configurar los valores clave de sus notificaciones locales en content.userInfo.
content.userInfo = ["isMyLocationNotification" : true] //you can set anythingLuego verifique el método de respuesta didReceive de UNUserNotificationCenterDelegate:
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { print(response.notification.request.content.userInfo) //you can check your notification types }En la sección de salida, usará los datos de información con la clave isMyLocationNotification. Ahora puede identificar que la notificación meteorológica es local o remota.