Todos los productos
Search
Centro de documentos

Mobile Platform as a Service:Integración con iOS

Última actualización: Sep 05, 2026

Este tema describe cómo integrar Mobile Push Service (MPS) con un cliente iOS.

Requisitos previos

Debe haber integrado su proyecto con mPaaS mediante integrating based on an existing project and using CocoaPods.

Procedimiento

Para utilizar MPS, complete los siguientes pasos:

  1. Después de integrar mPaaS mediante integrating based on an existing project and using CocoaPods, agregue la dependencia del componente MPS añadiendo mPaaS_pod "mPaaS_Push" al Podfile. Luego, ejecute pod install para agregar el SDK de MPS.

  2. Configure el proyecto. En la configuración de TARGETS de su proyecto, habilite las siguientes dos capacidades:

    • Capabilities > Push Notificationspush-ca

    • Capabilities > Background Modes > Remote notificationspush-back

  3. Utilice el SDK.

    Si integró el cliente iOS basándose en un proyecto existente mediante CocoaPods, complete las siguientes operaciones.

    1. Registre el deviceToken (opcional).

      El SDK de MPS solicita automáticamente el registro del deviceToken cuando se inicia la aplicación. Por lo general, no es necesario solicitar este registro manualmente. Sin embargo, en casos especiales, como cuando los controles de privacidad bloquean todas las solicitudes de red al inicio, debe activar nuevamente el registro del deviceToken después de conceder la autorización. El siguiente código muestra un ejemplo:

      - (void)registerRemoteNotification
      {
          // Register for push notifications
          if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10.0) {// 10.0+
              UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];
              center.delegate = self;
              [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
      
                      [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert|UNAuthorizationOptionSound|UNAuthorizationOptionBadge)
                                            completionHandler:^(BOOL granted, NSError * _Nullable error) {
                          // Enable or disable features based on authorization.
                          if (granted) {
                              dispatch_async(dispatch_get_main_queue(), ^{
                                  [[UIApplication sharedApplication] registerForRemoteNotifications];
                              });
                          }
                      }];
      
              }];
          } else {// 8.0, 9.0
              UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeBadge                                                                                         |UIUserNotificationTypeSound|UIUserNotificationTypeAlert) categories:nil];
              [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
              [[UIApplication sharedApplication] registerForRemoteNotifications];
          }
      }
    2. Obtenga el deviceToken y vincule el userId.

      El SDK de MPS de mPaaS encapsula la lógica de registro en el servidor APNs. El SDK realiza este registro automáticamente después de iniciar el programa. Puede recuperar el deviceToken emitido por APNs en el método de callback de registro exitoso. Posteriormente, puede llamar al método de interfaz de PushService para reportar y vincular el userId al núcleo de MPS.

      // import <PushService/PushService.h>
      - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
      {
          [[PushService sharedService] setDeviceToken:deviceToken];
          [[PushService sharedService] pushBindWithUserId:@"your userid(replace it)" completion:^(NSException *error) {
          }];
      
      }

      El SDK de MPS también proporciona la interfaz de desvinculación - (void)pushUnBindWithUserId:(NSString *)userId completion:(void (^)(NSException *error))completion; para desvincular el deviceToken del userId de la aplicación actual. Por ejemplo, puede llamar a esta interfaz después de que un usuario cambie de cuenta.

    3. Reciba mensajes push.

      Cuando el cliente recibe un mensaje push y el usuario toca para verlo, el sistema inicia la aplicación correspondiente. Puede manejar la lógica de recepción de mensajes push en el método de callback de AppDelegate.

      • Para sistemas anteriores a iOS 10, gestione los mensajes de la barra de notificaciones o los mensajes silenciosos de la siguiente manera:

          // Handle push cold start for iOS versions earlier than 10
          - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
          NSDictionary *userInfo = [launchOptions objectForKey: UIApplicationLaunchOptionsRemoteNotificationKey];
          if ([[[UIDevice currentDevice] systemVersion] doubleValue] < 10.0) {
              // Handle push cold start for iOS versions earlier than 10
          }
        
          return YES;
        }
        
          // Method for handling normal pushes when the app is in the foreground. Method for handling silent pushes when the app is in the foreground or background. Method for handling notification bar messages for systems earlier than iOS 10.
          - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler
          {
              //Process the received message
          }
      • Para iOS 10 y versiones posteriores, debe implementar los siguientes métodos delegados para escuchar los mensajes de la barra de notificaciones:

          // Register UNUserNotificationCenter delegate 
          if ([[[UIDevice currentDevice] systemVersion] doubleValue] >= 10.0) {
                  UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];
                  center.delegate = self;
            }
        
           //Receive remote push when the app is in the foreground
          - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
          {
              NSDictionary *userInfo = notification.request.content.userInfo;
        
              if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
                  //Receive remote push when the app is in the foreground
        
              } else {
                  //Receive local push when the app is in the foreground
        
              }
              completionHandler(UNNotificationPresentationOptionNone);
          }
        
          //Receive remote push when the app is in the background or during a cold start
          - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)(void))completionHandler
          {
              NSDictionary *userInfo = response.notification.request.content.userInfo;
        
              if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
                  //Receive remote push when the app is in the background or during a cold start
        
              } else {
                  //Receive local push when the app is in the foreground
        
              }
              completionHandler();
        
          }
    4. Rastree la tasa de apertura de mensajes.

      Para rastrear la tasa de apertura de mensajes en el cliente, debe llamar a la interfaz pushOpenLogReport de PushService (disponible en la versión 10.1.32 y posteriores) para reportar el evento de apertura cuando un usuario abre el mensaje. Una vez reportado este evento, puede consultar las estadísticas de tasa de apertura en la página Mobile Push Service > Overview de la consola de mPaaS.

      /**
       * The reporting interface for opening a push message, used to track the open rate of push messages
       * @param  userInfo The userInfo of the message
       * @return
       */
      - (void)pushOpenLogReport:(NSDictionary *)userInfo;
  4. Configure un certificado de push.

    Para enviar mensajes mediante la consola de MPS de mPaaS, debe configurar un certificado de push de APNs en la consola. Este certificado debe coincidir con la firma del cliente; de lo contrario, el cliente no recibirá mensajes push. Para obtener más información, consulte Configure an iOS push channel.

Siguientes pasos

  • Después de configurar el certificado de APNs en la consola de MPS de mPaaS, puede enviar mensajes push a la aplicación por dispositivo. MPS utiliza APNs de Apple para enviar mensajes a los clientes. Para obtener más información, consulte Push process for Apple and non-Chinese mainland Android devices.

  • Después de reportar el ID de usuario y que el servidor vincule al usuario con el dispositivo, puede enviar mensajes push a la aplicación por usuario.

Ejemplo de código

Haga clic aquí para descargar el paquete de código de ejemplo.

Enlaces relacionados

Envío de mensajes push de Live Activity

iOS 16.1 introdujo una nueva función: Live Activity. Esta función muestra actividades en tiempo real en la pantalla de bloqueo, lo que ayuda a los usuarios a mantenerse informados sobre el progreso de diversas actividades. En el proyecto principal, puede utilizar el framework ActivityKit para iniciar, actualizar y finalizar una Live Activity. También puede usar notificaciones push remotas para actualizar y finalizar una Live Activity. En la extensión del widget, puede usar SwiftUI y WidgetKit para crear la interfaz de usuario de la Live Activity. La función de actualización remota mediante push de Live Activity no admite certificados .p12. Debe configurar un certificado .p8.

Puede iniciar varias Live Activities en el mismo proyecto. Cada Live Activity tiene tokens diferentes.

Documentación oficial de Apple sobre Live Activity

Límites de Live Activity

  • Requiere iOS 16.1 o posterior.

  • Solo es compatible con dispositivos iPhone. No admite iPadOS, macOS, tvOS ni watchOS.

  • Una sola Live Activity puede ejecutarse durante un máximo de 8 horas. Pasadas las 8 horas, el sistema finaliza automáticamente la Live Activity, pero no se elimina inmediatamente de la pantalla de bloqueo.

  • Después de finalizar, el sistema la elimina automáticamente de la pantalla de bloqueo tras 4 horas.

  • El tamaño de los archivos de recursos debe cumplir con los requisitos. Para obtener más información, consulte la documentación para desarrolladores de Apple.

  • El contenido del push no puede superar los 4 KB.

Integración con el cliente

Configuración del proyecto para admitir Live Activity

  1. En el archivo Info.plist del proyecto principal, agregue un par clave-valor. Establezca la clave como NSSupportsLiveActivities y el valor como YES.

    image.png

  2. Cree una Widget Extension. Si su proyecto ya cuenta con una, omita este paso.

    image

    image

Implementación de código

  1. Cree un modelo.

    • En el código del proyecto principal, cree un nuevo archivo Swift. En este archivo, defina ActivityAttributes y Activity.ContentState según sea necesario. El siguiente código muestra un ejemplo.

    import SwiftUI
    import ActivityKit
    
    struct PizzaDeliveryAttributes: ActivityAttributes {
        public typealias PizzaDeliveryStatus = ContentState
      
        public struct ContentState: Codable, Hashable {
            var driverName: String
            var estimatedDeliveryTime: ClosedRange<Date>
            
            init(driverName: String, estimatedDeliveryTime: ClosedRange<Date>) {
                self.driverName = driverName
                self.estimatedDeliveryTime = estimatedDeliveryTime
            }
            init(from decoder: Decoder) throws {
                let container: KeyedDecodingContainer<PizzaDeliveryAttributes.ContentState.CodingKeys> = try decoder.container(keyedBy: PizzaDeliveryAttributes.ContentState.CodingKeys.self)
                self.driverName = try container.decode(String.self, forKey: PizzaDeliveryAttributes.ContentState.CodingKeys.driverName)
                if let deliveryTime = try? container.decode(TimeInterval.self, forKey: PizzaDeliveryAttributes.ContentState.CodingKeys.estimatedDeliveryTime) {
                    self.estimatedDeliveryTime = Date()...Date().addingTimeInterval(deliveryTime * 60)
                } else if let deliveryTime = try? container.decode(String.self, forKey: PizzaDeliveryAttributes.ContentState.CodingKeys.estimatedDeliveryTime) {
                    self.estimatedDeliveryTime = Date()...Date().addingTimeInterval(TimeInterval.init(deliveryTime)! * 60)
                } else {
                    self.estimatedDeliveryTime = try container.decode(ClosedRange<Date>.self, forKey: PizzaDeliveryAttributes.ContentState.CodingKeys.estimatedDeliveryTime)
                }
            }
        }
      
        var numberOfPizzas: Int
        var totalAmount: String
    }
    
    • Debe seleccionar tanto el target del proyecto principal como la Activity.

    • El sistema procesa los mensajes push recibidos. Los desarrolladores no pueden interceptarlos.

    • El ContentState contiene datos que se pueden actualizar dinámicamente. Al enviar una notificación de Live Activity, los nombres y tipos de parámetros para las actualizaciones dinámicas deben coincidir con los configurados en ContentState.

    • Si algunos datos requieren procesamiento, debe sobrescribir el método decoder de ActivityAttributes.ContentState.

  2. Cree la interfaz de usuario.

    En la Widget Extension, cree la interfaz de usuario de la Live Activity. Cree un Widget que devuelva una ActivityConfiguration.

    Implemente el código de la interfaz de usuario según sus necesidades.

    image

  3. Utilice WidgetBundle.

    Si la aplicación target admite tanto widgets como Live Activities, utilice WidgetBundle.

    import WidgetKit
    import SwiftUI
    
    @main
    structIslandBundle: WidgetBundle {
    varbody: someWidget {
    Island()
    IslandLiveActivity()
    }
    }
  4. Inicie la Live Activity.

    func startDeliveryPizza() {
        let pizzaDeliveryAttributes = PizzaDeliveryAttributes(numberOfPizzas: 1, totalAmount:"$99")
        let initialContentState = PizzaDeliveryAttributes.PizzaDeliveryStatus(driverName: "TIM", estimatedDeliveryTime: Date()...Date().addingTimeInterval(15 * 60))
        do {
            let deliveryActivity = try Activity<PizzaDeliveryAttributes>.request(
                attributes: pizzaDeliveryAttributes,
                contentState: initialContentState,
                pushType: .token)
        } catch (let error) {
            print("Error requesting pizza delivery Live Activity \(error.localizedDescription)")
        }
    }
  5. Envíe el token.

    Después de iniciar correctamente la Live Activity, obtenga el token de push para la Live Activity del sistema mediante el método pushTokenUpdates. Llame al método liveActivityBindWithActivityId:pushToken:filter:completion: de PushService para reportar el token.

    Al reportar el token, también debe proporcionar un identificador único para la Live Activity. El servidor utiliza este identificador para dirigir los envíos push. Debe personalizar este identificador y asegurarse de que sea único para cada Live Activity. El uso del mismo ID para diferentes Live Activities provocará errores en el envío. No cambie el identificador de una Live Activity activa, incluso cuando se actualice su token.

    Nota

    ActivityKit es un framework de Swift y no admite llamadas directas desde Objective-C. Al utilizar la API de este framework, debe llamarla desde un archivo Swift. Dado que el SDK de Push de mPaaS está escrito en Objective-C, debe crear un encabezado puente para llamar a sus métodos desde Swift. En el encabezado puente, importe: #import <MPPushSDK/MPPushSDK.h>.

    let liveactivityId = UserDefaults.standard.string(forKey: "pushTokenUpdates_id") ?? "defloutliveactivityId"
    Task {
        for await tokenData in deliveryActivity.pushTokenUpdates {
            let newToken = tokenData.map { String(format: "%02x", $0) }.joined()       
            PushService.shared().liveActivityBind(withActivityId: liveactivityId, pushToken: newToken, filter: .call) { excpt in
                guard let excpt = excpt else {
                    ///Reported successfully
                    return
                }
                if "callRepeat" == excpt.reason {
                    ///Repeated call, please ignore
                    print("pushTokenUpdates_id——Repeated call")
                } else {
                    ///Report failed
                }
            }
        }
    }

    Después de reportar el token correctamente, puede utilizar el identificador de la Live Activity para enviar actualizaciones.

    Nota

    Debido a que pushTokenUpdates en un iPhone puede llamarse varias veces, en escenarios con múltiples Live Activities, la creación de una nueva Live Activity puede provocar que se vuelva a llamar al método pushTokenUpdates de una Live Activity anterior. Por lo tanto, el SDK proporciona una función de filtrado controlada por el parámetro filter:

    • Cuando filter es MPPushServiceLiveActivityFilterAbandon, el SDK descarta automáticamente la llamada repetida sin ejecutar un callback.

    • Cuando filter es MPPushServiceLiveActivityFilterCall, el SDK descarta la solicitud repetida y proporciona un callback de error. En este caso, error.reason es @"callRepeat". Puede ignorar este error.

    • Cuando filter se establece en MPPushServiceLiveActivityFilterReRefuse, el SDK no realiza ningún filtrado interno.

    • Si falla un reporte, un intento posterior del cliente por reportar el mismo activityId y pushToken no se considera una llamada repetida.

    A continuación se muestra la definición de MPPushServiceLiveActivityFilterType:

    typedef NS_ENUM(NSInteger, MPPushServiceLiveActivityFilterType){
        MPPushServiceLiveActivityFilterAbandon,//Discard directly, no callback
        MPPushServiceLiveActivityFilterCall,//Filter this request, provide failure callback (callRepeat)
        MPPushServiceLiveActivityFilterRefuse//Do not filter
    };