Módulo responsável por entregar e exibir notificações segmentadas no aplicativo. Estas notificações podem ser apresentadas em 2 formatos:
- Push notification comum, com imagem ou carrossel de imagens.
- Inbox de mensagens.
Antes de começar
Para integrar o módulo de notifications da MDM, o aplicativo precisa ter push notifications da Apple habilitado.
Siga as instruções em Apple Developer para obter uma chave de criptografia e o ID da chave Apple.
Para integrar o módulo de notifications da MDM, siga os passos abaixo:
1. Acesse a aba Capabilities do Xcode e ative o serviço de Push Notifications:
2. Adicione o seguinte código em seu AppDelegate, no método applicationDidBecomeActive
em seu AppDelegate, logo após solicitar permissão para uso de Tracking:
Task {
if await ATTrackingManager.requestTrackingAuthorization() == .authorized {
do {
let granted = try await notificationCenter.requestAuthorization(options: [.alert, .badge, .sound])
if granted {
DispatchQueue.main.async { [self] in
UIApplication.shared.registerForRemoteNotifications()
MDMCore.start(withAppId: "SEU_APP_ID", kitModules: [MDMAppBehavior.self()])
}
}
} catch { }
}
}
3. Registre o token fornecido pelo iOS, implementando o método didRegisterForRemoteNotificationsWithDeviceToken
no seu AppDelegate:
MDMNotification.registerToken(deviceToken)
4. Remova o token da MDM implementando o método didFailToRegisterForRemoteNotificationsWithError
no seu AppDelegate:
MDMNotification.unregisterToken()
5. Para recebimento das notificações enviadas pela MDM, implemente o método didReceiveNotificationResponse
do delegate UNUserNotificationCenterDelegate em seu AppDelegate:
let userInfo = response.notification.request.content.userInfo
if MDMNotification.isMDMNotification(userInfo) {
MDMNotification.receive(userInfo)
} else {
// Process your notification here
}
completionHandler();
6. Para abertura das notificações enviadas pela MDM, implemente o método willPresentNotification
do delegate UNUserNotificationCenterDelegate em seu AppDelegate:
let userInfo = notification.request.content.userInfo
if MDMNotification.isMDMNotification(userInfo) {
MDMNotification.processNotification(userInfo)
} else {
// Open your notification here
}
completionHandler([.alert, .sound, .badge])
7. Para reportar o recebimento de notificações enviadas pela MDM, implemente a extensão para serviços de notificações, Notification Service Extension. Importante manter a mesma versão e linguagem do projeto:
8. Atualize o Podfile como mostrado abaixo, respeitando o nome dado na extension criada e em seguida execute o comando pod update no terminal.
target 'MDMNotificationService' do
# Comment the next line if you're not using Swift and don't want to use dynamic frameworks
use_frameworks!
# Pods for MDMNotificationService
pod 'MDMNotification'
end
9. Ative na aba Capabilities a opção App Groups, criando um grupo, preferencialmente com o nome do bundle identifier do target principal, precedido por group.:
10. Adicione ao Info.plist do seu target e da extension criada a chave NSGroupIdentifier
do tipo String preenchido com o nome do grupo criado, como mostra o exemplo abaixo:
<key>NSGroupIdentifier</key>
<string>NAME OF THE GROUP</string>
11. Adicione ao Info.plist da extension criada a chave NSAppTransportSecurity
do tipo Dictionary preenchido com a chave NSAllowsArbritaryLoads
de valor YES, como mostra o exemplo abaixo:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbritaryLoads</key>
<true/>
</dict>
12. Na extension criada, abra a classe NotificationService, importe o pacote MDMNotification
e estenda a classe MDMNotificationService
, como apresentado abaixo:
import MDMNotification
class NotificationService: MDMNotificationService {
// Your code here
}
13. Altere o conteúdo do método didReceiveNotificationRequest
como mostrado abaixo:
self.contentHandler = contentHandler
self.bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
if let bestAttemptContent = self.bestAttemptContent {
if MDMNotification.isMDMNotification(bestAttemptContent.userInfo) {
super.didReceive(request, withContentHandler: contentHandler)
} else {
// Your code here
contentHandler(bestAttemptContent)
}
}
14. Altere o conteúdo do método serviceExtensionTimeWillExpire
como mostrado abaixo:
if let contentHandler = self.contentHandler, let bestAttemptContent = self.bestAttemptContent {
if MDMNotification.isMDMNotification(bestAttemptContent.userInfo) {
super.serviceExtensionTimeWillExpire()
} else {
// Your code here
contentHandler(bestAttemptContent)
}
}
Para implementar a exibição de carrossel de imagens na notificação, siga os passos abaixo:
1. Para exibir notificações nos formatos imagem ou carrossel, implemente a extensão para conteúdos de notificações, Notification Content Extension. Importante manter a mesma versão e linguagem do projeto:
2. Atualize o Podfile como mostrado abaixo, respeitando o nome dado na extension criada e em seguida execute o comando pod update no terminal.
target 'MDMNotificationContent' do
# Comment the next line if you're not using Swift and don't want to use dynamic frameworks
use_frameworks!
# Pods for MDMNotificationContent
pod 'MDMNotification'
end
3. Ative na aba Capabilities a opção App Groups, selecionando o grupo criado:
4. Adicione ao Info.plist da extension criada a chave NSGroupIdentifier
do tipo String preenchido com o nome do grupo, como mostra o exemplo abaixo:
<key>NSGroupIdentifier</key>
<string>NAME OF THE GROUP</string>
5. Adicione ao Info.plist da extension criada a chave NSAppTransportSecurity
do tipo Dictionary preenchido com a chave NSAllowsArbritaryLoads
de valor YES, como mostra o exemplo abaixo:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbritaryLoads</key>
<true/>
</dict>
6. Na extension criada, abra o arquivo NotificationViewController, importe o pacote MDMNotification
e estenda a classe MDMNotificationViewController
, como apresentado abaixo:
import MDMNotification
class NotificationViewController: MDMNotificationViewController {
// Your code here
}
7. Altere o conteúdo do método didReceiveNotification
como mostrado abaixo:
self.isHandsPush = MDMNotification.isMDMNotification(notification.request.content.userInfo)
if self.isHandsPush {
super.didReceive(notification)
} else {
// Your code here
}
8. Altere o conteúdo do método didReceiveNotificationResponse
como mostrado abaixo:
if self.isHandsPush {
super.didReceive(response, completionHandler: completion)
} else {
// Your code here
}
9. Abra o Info.plist da extension criada e altere a chave UNNotificationExtensionCategory
para o tipo array e inclua os seguintes itens:
<key>NSExtensionAttributes</key>
<dict>
<key>UNNotificationExtensionUserInteractionEnabled</key><true/>
<key>UNNotificationExtensionCategory</key>
<array>
<string>carousel</string>
<string>image</string>
</array>
<key>UNNotificationExtensionInitialContentSizeRatio</key>
<real>1</real>
</dict>
Para implementar a exibição do Inbox, siga os passos abaixo:
Para a implementação do formato Inbox, adicione o seguinte código para quando desejar exibir o conteúdo:
let inboxTabBarController = InboxMainTabBarController()
inboxTabBarController.modalPresentationStyle = .fullScreen
present(inboxTabBarController, animated: true)
Para customização do título na UINavigationBar, adicione o seguinte código no método didFinishLaunchingWithOptions
de seu AppDelegate:
MDMInbox.setTitle("Hands Inbox")
Para customização da cor da UINavigationBar e UITabBar, adicione o seguinte código no método didFinishLaunchingWithOptions
de seu AppDelegate:
MDMInbox.setNavigationBarColor("#312683")
MDMInbox.setTabBarColor("#312683")
MDMInbox.setTintColor("#C8D400")
Para customização da cor de fundo, adicione o seguinte código no método didFinishLaunchingWithOptions
de seu AppDelegate:
MDMInbox.setBackgroundColor("#312683")
Para a implementação do formato Inbox, adicione o seguinte código para quando desejar exibir o conteúdo:
let bundle = Bundle(identifier: "br.com.hands.mdm.libs.ios.notification")
let storyboard = UIStoryboard(name: "MDMInBox", bundle: bundle)
if let navigationController = storyboard.instantiateViewController(withIdentifier: "MDMInboxNavigationController") as? UINavigationController {
navigationController.modalPresentationStyle = .fullScreen
self.present(navigationController, animated: true, completion: nil)
}
Opt-out
Para fazer o opt-out do módulo, basta chamar o seguinte comando:
MMDNotification.setOptOut(true)
Para desfazer o opt-out do módulo, basta chamar o seguinte comando:
MMDNotification.setOptOut(false)