Cambiamos el contenido de la aplicación de notificación iOS

Hola

En este artículo quiero compartir mi experiencia de usar una opción no obvia (al menos para mí) para cambiar el texto de notificación de la aplicación, enviando datos adicionales a través del UNUserNotificationCenter.

Espero que este artículo sea útil para principiantes en la programación para iOS en Swift. Se supone que tiene al menos algo de experiencia en programación con Swift para iOS. Usé Swift 5 y Xcode 10.2.1. Y así, comencemos.


Desafío


Tengo una aplicación que muestra las notificaciones del usuario. Una notificación consta de texto del cuerpo y texto de fondo.

Por lo tanto, la idea es mostrar primero al usuario solo el texto principal, y si el usuario desea conocer el texto secundario, debe hacer clic en el botón "mostrar" en la notificación.

Utilizo el siguiente método para mostrar una notificación (todas las explicaciones a continuación):

1. En primer lugar, debemos definir una instancia de UNUserNotificationCenter:

class NotificationService: NSObject, UNUserNotificationCenterDelegate { let notificationCenter = UNUserNotificationCenter.current() } 


2. A continuación, declaramos un método que usaremos para enviar notificaciones:
Mi método de solicitud de notificación
 // 1 //   ,      Tuple    . // showBody -     Bool,           . // withAction -     Bool,       ,   ""  . // atDate date -    Date,      ,      . func showNotification(with item: (String, String), showBody: Bool, withAction: Bool, atDate date: Date) { // 2 //    let content = UNMutableNotificationContent() // 3 //     let userActionsIdentifier = “showMe” // 4 //      . content.title = item.0 // 5 //    ,      false,  ,       . if showBody { content.body = item.1 } // 6 //     -    notificationCenter userInfo      . content.userInfo = [item.0: item.1] content.sound = UNNotificationSound.default // 7 //        withAction  true,      "Show me". if withAction { content.categoryIdentifier = userActionsIdentifier } // 8 //    ,        . let notificationID = item.0 // 9 //      . //       ,      . var dc = DateComponents() dc.hour = Calendar.current.component(.hour, from: date) dc.minute = Calendar.current.component(.minute, from: date) dc.second = Calendar.current.component(.second, from: date) // 10 //   .     ,       UNCalendarNotificationTrigger. let trigger = UNCalendarNotificationTrigger(dateMatching: dc, repeats: false) // 11 //        ,   . let request = UNNotificationRequest(identifier: notificationID, content: content, trigger: trigger) // 12 //     notificationCenter,     . notificationCenter.add(request) { (error) in error == nil ? print(“notifacation request was added at “, trigger.nextTriggerDate()!) : print(error.debugDescription) } // 13 //    .            .      . let action = UNNotificationAction(identifier: “showMe”, title: “Show me”, options: []) // 14 //   . let category = UNNotificationCategory(identifier:userActionsIdentifier, actions: [action], intentIdentifiers: [], options: []) // 15 //      notificationCenter. notificationCenter.setNotificationCategories([category]) } 



Cuando llamamos a este método, veremos una notificación en el momento que establezcamos.
Si el usuario retira la notificación, aparecerá el botón "Mostrar". Luego, el usuario debe hacer clic en este botón para ver el texto de fondo. Para ello, debemos utilizar el método de delegado UNUserNotificationCenterDelegate:

 func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { … } 


Entonces, el código que uso en el método de este delegado es el siguiente:

Mi método delegado
 func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { print(“didReceive response”) // 1 //   switch     switch response.actionIdentifier { case “showMe”: print(“showMe action”) // 2 //      userInfo,      showNotification   6,      String. let mainText = response.notification.request.content.userInfo.keys.first! as! String // 3 //       userInfo,      showNotification   6,       String. let subText = response.notification.request.content.userInfo.values.first! as! String // 4 //       showNotificationlet,    : // showBody    true,  withAction  false (       ). self.showNotification(with: (mainText, subText), showBody: true, withAction: false, atDate: Date(timeInterval: 3, since: Date())) default: print(“defaul action”) } completionHandler() } 



Y así es como se ve:



Dentro del proyecto (que puede descargar desde el siguiente enlace) hay algo más de código, pero la esencia de la idea se describe en este artículo.

Gracias

Enlace al proyecto

Source: https://habr.com/ru/post/451454/


All Articles