Alteramos o conteúdo do aplicativo de notificação iOS

Oi

Neste artigo, quero compartilhar minha experiência de usar uma opção não óbvia (pelo menos para mim) para alterar o texto de notificação do aplicativo, enviando dados adicionais por meio do UNUserNotificationCenter.

Espero que este artigo seja útil para iniciantes em programação para iOS no Swift. Supõe-se que você tenha pelo menos alguma experiência em programação com o Swift para iOS. Eu usei o Swift 5 e o Xcode 10.2.1. E então, vamos começar.


Desafio


Eu tenho um aplicativo que mostra as notificações do usuário. Uma notificação consiste em texto do corpo e texto em segundo plano.

Portanto, a idéia é primeiro mostrar ao usuário apenas o texto principal e, se ele quiser conhecer o texto secundário, ele deve clicar no botão "mostrar" na notificação.

Eu uso o seguinte método para mostrar uma notificação (todas as explicações abaixo):

1. Antes de tudo, devemos definir uma instância do UNUserNotificationCenter:

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


2. Em seguida, declaramos um método que usaremos para enviar notificações:
Meu método de solicitação de notificação
 // 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]) } 



Quando chamamos esse método, veremos uma notificação no momento que definimos.
Se o usuário puxar a notificação para baixo, o botão "Mostre-me" será exibido. Em seguida, o usuário deverá clicar neste botão para ver o texto de segundo plano. Para fazer isso, devemos usar o método de delegação UNUserNotificationCenterDelegate:

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


Portanto, o código que eu uso no método deste delegado é o seguinte:

Meu método de delegação
 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() } 



E aqui está o que parece:



Dentro do projeto (que você pode baixar no link abaixo), há mais código, mas a essência da ideia é descrita neste artigo.

Obrigada

Link para o projeto

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


All Articles