Módulo responsable de entregar y mostrar notificaciones específicas en la aplicación. Estas notificaciones se pueden presentar en 2 formatos:
- Notificación push común con imagen o carrusel de imágenes.
- Inbox mensajes.
Antes de empezar
Para integrar el módulo de notificaciones de MDM, la aplicación debe tener push notifications con Apple integrado.
Siga las instrucciones en Apple Developer para obtener una clave de cifrado y una ID de clave de Apple.
Para integrar el módulo de notificaciones de MDM, siga los siguientes pasos:
1. Acceda a la pestaña Capabilities de Xcode y active el servicio de Push Notifications:
2. Después de iniciar el módulo, agregue el siguiente código en su AppDelegate, en el método didFinishLaunchingWithOptions
, para solicitar permiso de notificación de iOS:
self.notificationCenter = UNUserNotificationCenter.current()
self.notificationCenter.delegate = self
self.notificationCenter(options: [.alert, .sound]) { (granted, error) in
if granted {
OperationQueue.main.addOperation({
if !application.isRegisteredForRemoteNotifications {
application.registerForRemoteNotifications()
}
})
}
}
self.notificationCenter = [UNUserNotificationCenter currentNotificationCenter];
self.notificationCenter.delegate = self;
[self.notificationCenter requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound) completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (granted) {
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
if (![application isRegisteredForRemoteNotifications]) {
[application registerForRemoteNotifications];
}
}];
}
}];
3. Registre el token provisto por iOS, implementando el método didRegisterForRemoteNotificationsWithDeviceToken
en su AppDelegate:
MDMNotification.registerToken(deviceToken)
[MDMNotification registerToken:deviceToken];
4. Quite el token de MDM implementando el método didFailToRegisterForRemoteNotificationsWithError
en su AppDelegate:
MDMNotification.unregisterToken()
[MDMNotification unregisterToken];
5. Para recibir notificaciones enviadas por MDM, implemente el método didReceiveNotificationResponse
del delegado UNUserNotificationCenterDelegate en su AppDelegate:
let userInfo = response.notification.request.content.userInfo
if MDMNotification.isMDMNotification(userInfo) {
MDMNotification.processNotification(userInfo)
} else {
// Process your notification here
}
completionHandler();
NSDictionary *userInfo = response.notification.request.content.userInfo;
if ([MDMNotification isMDMNotification:userInfo]) {
[MDMNotification processNotification:userInfo];
} else {
// Process your notification here
}
completionHandler();
6. Para abrir las notificaciones enviadas por MDM, implemente el método willPresentNotification
del delegado UNUserNotificationCenterDelegate en su AppDelegate:
let userInfo = notification.request.content.userInfo
if MDMNotification.isMDMNotification(userInfo) {
MDMNotification.processNotification(userInfo)
} else {
// Open your notification here
}
NSDictionary *userInfo = notification.request.content.userInfo;
if ([MDMNotification isMDMNotification:userInfo]) {
[MDMNotification processNotification:userInfo];
} else {
// Open your notification here
}
7. Para informar la recepción de notificaciones enviadas por MDM, implemente la Extensión del servicio de notificaciones. Importante para mantener la misma versión e idioma del proyecto:
8. Actualice Podfile como se muestra a continuación, respetando el nombre dado en la extensión creada y luego ejecute el comando pod update en el 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. Active la opción App Grupos en la pestaña Capabilities, creando un grupo, preferiblemente con el nombre del identificador de paquete del target principal, precedido por el grupo:
10. Agregar a la lista Info.plist de su target y extensión creó la clave NSGroupIdentifier
de tipo String con el nombre del grupo creado, como se muestra en el siguiente ejemplo:
<key>NSGroupIdentifier</key>
<string>NAME OF THE GROUP</string>
11. Agregue a la extensión Info.plist creó la clave NSAppTransportSecurity
del tipo Dictionary con la clave NSAllowsArbritaryLoads
del valor YES, como se muestra en el siguiente ejemplo:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbritaryLoads</key>
<true/>
</dict>
12. En la extensión creada, abra la clase NotificationService, importe el paquete MDMNotification
extienda la clase MDMNotificationService
, como se muestra a continuación:
import MDMNotification
class NotificationService: MDMNotificationService {
// Your code here
}
#import <MDMNotification/MDMNotification.h>
@interface NotificationService : MDMNotificationService
@end
13. Cambie el contenido del método didReceiveNotificationRequest
como se muestra a continuación:
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)
}
}
self.contentHandler = contentHandler;
self.bestAttemptContent = [request.content mutableCopy];
if ([MDMNotification isMDMNotification:self.bestAttemptContent.userInfo]) {
[super didReceiveNotificationRequest:request withContentHandler:contentHandler];
} else {
// Your code here
self.contentHandler(self.bestAttemptContent);
}
14. Cambie el contenido del método serviceExtensionTimeWillExpire
como se muestra a continuación:
if let contentHandler = self.contentHandler, let bestAttemptContent = self.bestAttemptContent {
if MDMNotification.isMDMNotification(bestAttemptContent.userInfo) {
super.serviceExtensionTimeWillExpire()
} else {
// Your code here
contentHandler(bestAttemptContent)
}
}
if ([MDMNotification isMDMNotification:self.bestAttemptContent.userInfo]) {
[super serviceExtensionTimeWillExpire];
} else {
// Your code here
self.contentHandler(self.bestAttemptContent);
}
Para implementar la visualización del carrusel de imágenes en la notificación, siga los pasos a continuación:
1. Para mostrar notificaciones en formatos de imagen o carrusel, implemente la extensión Extensión de contenido de notificación. Importante para mantener la misma versión e idioma del proyecto:
2. Actualice Podfile como se muestra a continuación, respetando el nombre dado en la extensión creada y luego ejecute el comando pod update en el 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. Active en la pestaña Capabilities la opción App Grupos, seleccionando el grupo creado:
4. Agregar a la extensión Info.plist creó la clave NSGroupIdentifier
de tipo String con el nombre del grupo, como se muestra en el siguiente ejemplo:
<key>NSGroupIdentifier</key>
<string>NAME OF THE GROUP</string>
5. Agregue a la extensión Info.plist creó la clave NSAppTransportSecurity
del tipo Dictionary con la clave NSAllowsArbritaryLoads
del valor YES, como se muestra en el siguiente ejemplo:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbritaryLoads</key>
<true/>
</dict>
6. En la extensión creada, abra el archivo NotificationViewController, importe el paquete MDMNotification
extienda la clase MDMNotificationViewController
, como se muestra a continuación:
import MDMNotification
class NotificationViewController: MDMNotificationViewController {
// Your code here
}
#import <MDMNotification/MDMNotification.h>
@interface NotificationViewController : MDMNotificationViewController
@end
7. Cambie el contenido del método didReceiveNotification
como se muestra a continuación:
self.isHandsPush = MDMNotification.isMDMNotification(notification.request.content.userInfo)
if self.isHandsPush {
super.didReceive(notification)
} else {
// Your code here
}
self.isHandsPush = [MDMNotification isMDMNotification:notification.request.content.userInfo];
if (self.isHandsPush) {
[super didReceiveNotification:notification];
} else {
// Your code here
}
8. Cambie el contenido del método didReceiveNotificationResponse
como se muestra a continuación:
if self.isHandsPush {
super.didReceive(response, completionHandler: completion)
} else {
// Your code here
}
if (self.isHandsPush) {
[super didReceiveNotificationResponse:response completionHandler:completion];
} else {
// Your code here
}
9. Abra la extensión Info.plist de la extensión y cambie la clave UNNotificationExtensionCategory
al tipo de array y agregue estos dos elementos nuevos:
<key>UNNotificationExtensionCategory</key>
<array>
<string>carousel</string>
<string>image</string>
</array>
Para implementar la Inbox, siga los pasos a continuación:
Para la personalización del título UINavigationBar, agregue el siguiente código en el método didFinishLaunchingWithOptions
de su AppDelegate:
MDMInbox.setTitle("Hands Inbox")
[MDMInbox setTitle:@"Hands Inbox"];
Para la personalización del color UINavigationBar y UITabBar, agregue el siguiente código al método didFinishLaunchingWithOptions
de su AppDelegate:
MDMInbox.setNavigationBarColor("#312683")
MDMInbox.setTabBarColor("#312683")
MDMInbox.setTintColor("#C8D400")
[MDMInbox setNavigationBarColor:@"#312683"];
[MDMInbox setTabBarColor:@"#312683"];
[MDMInbox setTintColor:@"#C8D400"];
Para la personalización del color de fondo, agregue el siguiente código en el método didFinishLaunchingWithOptions
de su AppDelegate:
MDMInbox.setBackgroundColor("#312683")
[MDMInbox setBackgroundColor:@"#312683"];
Para la implementación del formato de la Bandeja de entrada, agregue el siguiente código para cuando desee mostrar contenido:
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)
}
NSBundle *bundle = [NSBundle bundleWithIdentifier:@"br.com.hands.mdm.libs.ios.notification"];
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MDMInBox" bundle:bundle];
UINavigationController *navigationController = [storyboard instantiateViewControllerWithIdentifier:@"MDMInboxNavigationController"];
navigationController.modalPresentationStyle = UIModalPresentationFullScreen;
[self presentViewController:navigationController animated:YES completion:nil];
Opt-out
Para inhabilitar el módulo, simplemente ejecute el siguiente comando:
MMDNotification.setOptOut(true)
[MDMNotification setOptOut:YES];
Para deshacer la exclusión voluntaria del módulo, simplemente llame al siguiente comando:
MMDNotification.setOptOut(false)
[MDMNotification setOptOut:NO];