iOS SDK Integration Guide

Versión aplicable

Este artículo corresponde a la versión del SDK de iOS de MTPush: v3.0.0 y posteriores.

Archivo de recursos

Nombre del paquete: engagelab-ios-{número de versión}

A partir de la versión 4.3.3, ya no se proporcionará el paquete .a. Solo se ofrecerán paquetes .xcframework.

  • Carpeta lib: contiene mtpush-ios-x.x.x.xcframework, mtpush-extension-ios-x.x.x.xcframework. (Nota: APNs no es compatible con simuladores).
  • Archivo README: instrucciones relacionadas con el SDK
  • Carpeta demo: ejemplos

Obtención de información de la aplicación

Después de crear una aplicación en la consola, se genera automáticamente un AppKey para identificar la aplicación.

Configuración del proyecto

Importar el SDK

Importación con Cocoapods

pod 'MTPush' Nota: Si no puede importar la versión más reciente, ejecute el comando `pod repo update master` para actualizar la biblioteca de pods local y, a continuación, vuelva a ejecutar `pod 'MTPush'`.
              
                  pod 'MTPush'

    Nota: Si no puede importar la versión más reciente, ejecute el comando `pod repo update master` para actualizar la biblioteca de pods local y, a continuación, vuelva a ejecutar `pod 'MTPush'`.

            
Este bloque de código se muestra en una ventana flotante
  • Si se necesita instalar la versión especificada, utilizar el siguiente método (tomando MTPush 3.5.0 como ejemplo):
pod 'MTPush', '3.5.0'
              
                  pod 'MTPush', '3.5.0'

            
Este bloque de código se muestra en una ventana flotante

Importación manual

  • Descomprimir el paquete del SDK; en Xcode, seleccionar "Add files to 'Your project name'...", y añadir mtpush-ios-x.x.x.xcframework al directorio del proyecto.
  • Añadir Framework
    • CFNetwork.framework
    • CoreFoundation.framework
    • CoreTelephony.framework
    • SystemConfiguration.framework
    • CoreGraphics.framework
    • Foundation.framework
    • UIKit.framework
    • Security.framework
    • libz.tbd
    • UserNotifications.framework
    • libresolv.tbd
    • libsqlite3.tbd

Build Settings

Si el proyecto requiere compatibilidad con sistemas operativos iOS anteriores a 7.0, acceder a Build Settings y desactivar la opción bitCode. De lo contrario, no se compilará correctamente.

  • Configurar User Header Search Paths y Library Search Paths en Search Paths. Por ejemplo, si la carpeta del SDK (el valor predeterminado es lib) está al mismo nivel que el archivo del proyecto, establecer este parámetro en $(SRCROOT)/{Nombre de la carpeta donde se encuentra la biblioteca estática}.

Capabilities

Si se desarrolla con Xcode 8 o superior, habilitar la opción Capabilities->Push Notifications en el Application Target, tal como se muestra aquí: 1.png
Si se desarrolla en un entorno Xcode 10 o superior, habilitar la opción Capabilities-> Access WIFI Infomation en el Application Target.
image.png

Añadir un archivo de encabezado

Añadir el siguiente código en la ubicación del archivo de encabezado referenciado por AppDelegate.m.

// import MTPush Function required header file #import "MTPushService.h" // iOS10 Register the required header file for APNs #ifdef NSFoundationVersionNumber_iOS_9_x_Max #import <UserNotifications/UserNotifications.h> #endif // Header files to introduce if you need to use idfa functionality (optional) #import <AdSupport/AdSupport.h>
              
              // import MTPush Function required header file
#import "MTPushService.h"
// iOS10 Register the required header file for APNs
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
// Header files to introduce if you need to use idfa functionality (optional)
#import <AdSupport/AdSupport.h>

            
Este bloque de código se muestra en una ventana flotante

Añadir el Delegate

Añadir un Delegate al AppDelegate. Consultar el siguiente código:

@interface AppDelegate ()<MTPushRegisterDelegate> @end
              
              @interface AppDelegate ()<MTPushRegisterDelegate>

@end

            
Este bloque de código se muestra en una ventana flotante

Añadir el código de inicialización

Añadir el código de inicialización de APNs

Añadir el siguiente código en -(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

//Required MTPushRegisterEntity * entity = [[MTPushRegisterEntity alloc] init]; entity.types = MTPushAuthorizationOptionAlert|MTPushAuthorizationOptionSound|MTPushAuthorizationOptionProvidesAppNotificationSettings; if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) { // Customizations can be added categories // NSSet<UNNotificationCategory *> *categories for iOS10 or later // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9 } [MTPushService registerForRemoteNotificationConfig:entity delegate:self];
              
                //Required
 
    MTPushRegisterEntity * entity = [[MTPushRegisterEntity alloc] init];
  entity.types = MTPushAuthorizationOptionAlert|MTPushAuthorizationOptionSound|MTPushAuthorizationOptionProvidesAppNotificationSettings;
  if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
    // Customizations can be added categories
    // NSSet<UNNotificationCategory *> *categories for iOS10 or later
    // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
  }
  [MTPushService registerForRemoteNotificationConfig:entity delegate:self];

            
Este bloque de código se muestra en una ventana flotante

Añadir el código de inicialización de MTPush

Añadir el siguiente código en -(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

// Optional // Get the IDFA // To use the IDFA function, add this code and fill in the advertisingIdentifier parameter for the initialization method NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString]; // Required // init Push [MTPushService setupWithOption:launchOptions appKey:appKey channel:channel apsForProduction:isProduction advertisingIdentifier:advertisingId];
              
              // Optional
// Get the IDFA
// To use the IDFA function, add this code and fill in the advertisingIdentifier parameter for the initialization method
NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];

// Required
// init Push
[MTPushService setupWithOption:launchOptions appKey:appKey
                      channel:channel
             apsForProduction:isProduction
        advertisingIdentifier:advertisingId];

            
Este bloque de código se muestra en una ventana flotante
Descripción de parámetros
  • appKey
    • Garantizar que el appkey configurado en la aplicación sea el mismo que el generado después de crear la aplicación en la consola.
  • channel
    • Especificar el canal de descarga del paquete de la aplicación. Para facilitar las estadísticas por canal, se puede definir el valor específico, por ejemplo, App Store.
  • apsForProduction
    • Este parámetro identifica el entorno del certificado de APNs utilizado por la aplicación actual.
    • 0 (valor predeterminado) indica que se utiliza un certificado de desarrollo, y 1 indica que se utiliza un certificado de producción para publicar aplicaciones.
    • Nota: el valor de este campo debe ser el mismo que el entorno del certificado configurado en Code Signing dentro de Build Settings.

APNs se registra correctamente y se informa el DeviceToken.

Consejos: Puede iniciar sesión en EngageLab sin llamar a este método. Sin embargo, las notificaciones de APNs no estarán disponibles; solo podrá utilizar los mensajes personalizados.

Implementar el método de devolución de llamada en AppDelegate.m y añadir el código dentro del método de devolución de llamada:

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { /// Required - registered DeviceToken [MTPushService registerDeviceToken:deviceToken]; }
              
              - (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {

  /// Required - registered DeviceToken
  [MTPushService registerDeviceToken:deviceToken];
}

            
Este bloque de código se muestra en una ventana flotante

Implementar la interfaz de error de registro de APNs (opcional)

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error { //Optional NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error); [MTPushService registerDeviceToken:deviceToken]; }
              
              - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
  //Optional
  NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
   [MTPushService registerDeviceToken:deviceToken];
}

            
Este bloque de código se muestra en una ventana flotante

Añadir un método de devolución de llamada para gestionar notificaciones de APNs

Implementar el método de devolución de llamada en AppDelegate.m y añadir el código dentro del método de devolución de llamada:

#pragma mark- MTPushRegisterDelegate // iOS 12 Support - (void)mtpNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification{if (notification && [notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {// Directly enter the application from the notification interface.}else{// Enter the application from the notification settings interface.} } // iOS 10 Support - (void)mtpNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler { // Required NSDictionary * userInfo = notification.request.content.userInfo; if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {[MTPushService handleRemoteNotification:userInfo]; } completionHandler(UNNotificationPresentationOptionAlert); // To execute this method, choose whether to Alert the user or not. There are three types of Badge, Sound, and alert that can be set } // iOS 10 Support - (void)mtpNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler { // Required NSDictionary * userInfo = response.notification.request.content.userInfo; if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {[MTPushService handleRemoteNotification:userInfo]; } completionHandler(); // The system requires this method to be executed} - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { // Required, iOS 7 Support [MTPushService handleRemoteNotification:userInfo]; completionHandler(UIBackgroundFetchResultNewData); } - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo { // Required, For systems with less than or equal to iOS 6 [MTPushService handleRemoteNotification:userInfo]; }
              
              #pragma mark- MTPushRegisterDelegate

// iOS 12 Support
- (void)mtpNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification{if (notification && [notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {// Directly enter the application from the notification interface.}else{// Enter the application from the notification settings interface.}
}

// iOS 10 Support
- (void)mtpNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
  // Required
  NSDictionary * userInfo = notification.request.content.userInfo;
  if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {[MTPushService handleRemoteNotification:userInfo];
  }
  completionHandler(UNNotificationPresentationOptionAlert); // To execute this method, choose whether to Alert the user or not. There are three types of Badge, Sound, and alert that can be set
}

// iOS 10 Support
- (void)mtpNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
  // Required
  NSDictionary * userInfo = response.notification.request.content.userInfo;
  if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {[MTPushService handleRemoteNotification:userInfo];
  }
  completionHandler();	// The system requires this method to be executed}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {

  // Required, iOS 7 Support
  [MTPushService handleRemoteNotification:userInfo];
  completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {

  // Required, For systems with less than or equal to iOS 6
  [MTPushService handleRemoteNotification:userInfo];
}

            
Este bloque de código se muestra en una ventana flotante

Añadir un método de devolución de llamada para gestionar mensajes personalizados de MTPush

Para utilizar la funcionalidad de mensajes personalizados de MTPush, consultar la 【Guía de API de iOS】 para implementar devoluciones de llamada de procesamiento de mensajes personalizados.

Ejecución correcta

Depurar el proyecto. Si la consola muestra el siguiente registro, la integración se ha realizado correctamente.

2016-08-19 17:12:12.745823 219b28[1443:286814] | MTP | I - [MTCORETcpEventController] ----- login result ----- uid:123456 registrationID:171976fa8a8620a14a4 idc:0
              
              2016-08-19 17:12:12.745823 219b28[1443:286814] | MTP | I - [MTCORETcpEventController] 
----- login result -----
uid:123456 
registrationID:171976fa8a8620a14a4 
idc:0

            
Este bloque de código se muestra en una ventana flotante

Si se encuentra algún problema durante la depuración, consultar la 【Guía de depuración del SDK de iOS】.

Funciones avanzadas

Escucha de eventos relacionados con el SDK de MTPush

Se recomienda que los desarrolladores incluyan los siguientes tipos de notificaciones proporcionadas en la API:

extern NSString *const kMTCNetworkIsConnectingNotification; // Estableciendo conexión
extern NSString * const kMTCNetworkDidSetupNotification; // Conexión establecida
extern NSString * const kMTCNetworkDidCloseNotification; // Conexión cerrada
extern NSString * const kMTCNetworkDidRegisterNotification; // Registro exitoso
extern NSString *const kMTCNetworkFailedRegisterNotification; // Fallo en el registro
extern NSString * const kMTCNetworkDidLoginNotification; // Inicio de sesión exitoso

Consejos útiles: Añada y registre el método de notificación kMTCNetworkDidLoginNotification y obtenga el ID de registro (Registration id) en este método; también puede llamar al método registrationIDCompletionHandler: y obtenerlo a través del completionHandler.

extern NSString * const kMTCNetworkDidReceiveMessageNotification; // Mensaje personalizado recibido (no APNs)
La transferencia de datos de kMTCNetworkDidReceiveMessageNotification se puede obtener mediante userInfo en NSNotification, incluyendo título, contenido e información extra, etc. Por favor, consulte el documento: iOS SDK API

Servicio de estadísticas de notificaciones

Consejos útiles: Notification Service Extension es una nueva característica en iOS 10, controlada por el campo mutable-content. Si utiliza la consola web para realizar el push, marque la opción mutable-content en Configuración opcional. Si utiliza una API RESTFul para realizar el push, establezca el campo mutable-content en true.

Los desarrolladores pueden usar el SDK de Notification Service Extension para informar del estado de entrega de cada mensaje de APNs. Nota: los datos de Impressions que se muestran en la consola de EngageLab se obtienen a partir de los datos de entrega informados aquí.

alt text

Cómo usarlo:

  • Crear un Service Extension Service. Para obtener más información, consultar iOS 10 Service Extension.
  • Importar el archivo mtpush-extension-ios-xxx.xcframework en el proyecto de Service Extension.
  • Añadir Framework: libz.tbd y libresolv.tbd.
  • Llamar a [mtpushSetAppkey:] para configurar el appkey. Tener en cuenta que este appkey debe ser el mismo que el appkey de la aplicación de EngageLab.
  • Llamar al método [mtpushReceiveNotificationRequest:] para informar de APNs; las estadísticas se procesarán correctamente. Mostrar el APNs en la devolución de llamada del bloque del método.

Para ver ejemplos de uso más específicos, consultar el código de demostración incluido en el paquete zip de la versión. Documento de referencia:iOS SDK API

Push de VoIP

  • Introducido en iOS 8, el push de VoIP basado en el marco PushKit permite que la aplicación del usuario se active y ejecute código incluso cuando está finalizada.
  • VoIP no distingue entre certificados de desarrollo y producción. Tanto Apple Push Notification service SSL (Sandbox & Production) como VoIP Services Certificate admiten push de VoIP.

Añadir la biblioteca PushKit.Framework

  • Incluir la biblioteca PushKit.framework en Xcode Build Phases - Link Binary With Libraries.
  • Importar el archivo de encabezado #import <PushKit/PushKit.h>.
  • Implementar el protocolo PKPushRegistryDelegate en AppDelegate.

Añadir el permiso de VoIP

En Project-> Capabilities->Background Modes, activar la opción Voice over IP.

Implementación de código

  • Implementar el registro de VoIP en el método didFinishLaunchingWithOptions.
- (void)voipRegistration{ dispatch_queue_t mainQueue = dispatch_get_main_queue(); PKPushRegistry *voipRegistry = [[PKPushRegistry alloc] initWithQueue:mainQueue]; voipRegistry.delegate = self; // Set the push type to VoIP voipRegistry.desiredPushTypes = [NSSet setWithObject:PKPushTypeVoIP]; }
              
              - (void)voipRegistration{
  dispatch_queue_t mainQueue = dispatch_get_main_queue();
  PKPushRegistry *voipRegistry = [[PKPushRegistry alloc] initWithQueue:mainQueue];
  voipRegistry.delegate = self;
  // Set the push type to VoIP
  voipRegistry.desiredPushTypes = [NSSet setWithObject:PKPushTypeVoIP];
}

            
Este bloque de código se muestra en una ventana flotante
  • Enviar el token
/// System returns VoipToken, report to Engagelab server - (void)pushRegistry:(PKPushRegistry *)registry didUpdatePushCredentials:(PKPushCredentials *)pushCredentials forType:(PKPushType)type{ if (type == PKPushTypeVoIP) { [MTPushService registerVoipToken:pushCredentials.token]; } }
              
              /// System returns VoipToken, report to Engagelab server
- (void)pushRegistry:(PKPushRegistry *)registry didUpdatePushCredentials:(PKPushCredentials *)pushCredentials forType:(PKPushType)type{
   if (type == PKPushTypeVoIP) {
    [MTPushService registerVoipToken:pushCredentials.token];
   }
}

            
Este bloque de código se muestra en una ventana flotante
  • Al recibir un push de VoIP, llamar a la interfaz de acuse de recibo para contabilizar las entregas de VoIP.
- (void)pushRegistry:(PKPushRegistry *)registry didReceiveIncomingPushWithPayload:(PKPushPayload *)payload forType:(PKPushType)type{ if (type == PKPushTypeVoIP) { // Submit receipt to Engagelab server [MTPushService handleVoipNotification:payload.dictionaryPayload]; } } - (void)pushRegistry:(PKPushRegistry *)registry didReceiveIncomingPushWithPayload:(PKPushPayload *)payload forType:(PKPushType)type withCompletionHandler:(void(^)(void))completion{ if (type == PKPushTypeVoIP) { // Submit receipt to Engagelab server [MTPushService handleVoipNotification:payload.dictionaryPayload]; } }
              
              - (void)pushRegistry:(PKPushRegistry *)registry didReceiveIncomingPushWithPayload:(PKPushPayload *)payload forType:(PKPushType)type{
  if (type == PKPushTypeVoIP) {
    // Submit receipt to Engagelab server
    [MTPushService handleVoipNotification:payload.dictionaryPayload];
  }
}

- (void)pushRegistry:(PKPushRegistry *)registry didReceiveIncomingPushWithPayload:(PKPushPayload *)payload forType:(PKPushType)type withCompletionHandler:(void(^)(void))completion{
   if (type == PKPushTypeVoIP) {
    // Submit receipt to Engagelab server
    [MTPushService handleVoipNotification:payload.dictionaryPayload];
   }
}

            
Este bloque de código se muestra en una ventana flotante

Soporte técnico

Cuando se produzcan problemas durante la integración

  • Leer detenidamente el documento para comprobar si hay alguna omisión.
  • Se puede acceder a EngageLab para buscar una pregunta similar. Para resolver el problema más rápidamente, proporcionar la siguiente información al solicitar ayuda:
    • El producto sobre el que se necesita consultar es MTPush y si se utilizan otros productos de EngageLab.
    • Qué API se está llamando, los parámetros que se están pasando, el mensaje de error completo y el momento en que se produjo la excepción.
    • Si no se recibe ningún mensaje, proporcionar el Appkey de la aplicación, el Message ID del mensaje y el registration ID del dispositivo.
    • Si el fallo está causado por el SDK, proporcionar la versión correspondiente del SDK y los registros completos. Cargar la información de registro mediante un archivo TXT.
    • El dispositivo con anomalías es iOS. Proporcionar el modelo y el sistema específicos.
Icon Solid Transparent White Qiyu
Contacto