Guía de integración básica del SDK de iOS 7.0+
Esta sección contiene información sobre cómo integrar el SDK de Pushwoosh en su aplicación de iOS.
Prerrequisitos
Anchor link toPara integrar el SDK de iOS de Pushwoosh en su aplicación, necesitará lo siguiente:
Pasos de integración
Anchor link to1. Instalación
Anchor link toPuede integrar el SDK de Pushwoosh en su aplicación utilizando Swift Package Manager o CocoaPods.
Swift Package Manager
Anchor link toEn la sección Package Dependencies, agregue el siguiente paquete:
https://github.com/Pushwoosh/Pushwoosh-XCFrameworkPara usar el SDK de iOS de Pushwoosh, asegúrese de agregar los siguientes cuatro frameworks a su objetivo de aplicación al integrar a través de Swift Package Manager:
PushwooshFrameworkPushwooshCorePushwooshBridgePushwooshLiveActivities

CocoaPods
Anchor link toAbra su Podfile y agregue la dependencia:
# Descomente la siguiente línea para definir una plataforma global para su proyecto# platform :ios, '9.0'
target 'MyApp' do # Comente la siguiente línea si no quiere usar frameworks dinámicos use_frameworks!
pod 'PushwooshXCFramework'
endLuego, en la terminal, ejecute el siguiente comando para instalar las dependencias:
pod install2. Capacidades
Anchor link toPara habilitar las Notificaciones Push en su proyecto, necesita agregar ciertas capacidades.
En la sección Signing & Capabilities, agregue las siguientes capacidades:
Push NotificationsBackground Modes. Después de agregar esta capacidad, marque la casilla paraRemote notifications.
Si tiene la intención de usar Notificaciones Sensibles al Tiempo (iOS 15+), agregue también la capacidad Time Sensitive Notifications.
3. Código de inicialización
Anchor link toAppDelegate
Anchor link toAgregue el siguiente código a su clase AppDelegate:
import SwiftUIimport PushwooshFramework
@mainstruct MyApp: App { // Registrar AppDelegate como UIApplicationDelegate @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene { WindowGroup { ContentView() } }}
class AppDelegate: NSObject, UIApplicationDelegate, PWMessagingDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Código de inicialización // Establecer delegado personalizado para el manejo de push Pushwoosh.configure.delegate = self
// Registrarse para notificaciones push Pushwoosh.configure.registerForPushNotifications()
return true }
// Manejar token recibido de APNS func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { Pushwoosh.configure.handlePushRegistration(deviceToken) }
// Manejar error al recibir el token func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { Pushwoosh.configure.handlePushRegistrationFailure(error) }
//para notificaciones push silenciosas func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { Pushwoosh.configure.handlePushReceived(userInfo) completionHandler(.noData) }
// Se dispara cuando se recibe un push func pushwoosh(_ pushwoosh: Pushwoosh, onMessageReceived message: PWMessage) { print("onMessageReceived: ", message.payload!.description) }
// Se dispara cuando un usuario toca la notificación func pushwoosh(_ pushwoosh: Pushwoosh, onMessageOpened message: PWMessage) { print("onMessageOpened: ", message.payload!.description) }}
struct ContentView: View { var body: some View { Text("Pushwoosh with SwiftUI") .padding() }}import PushwooshFramework
@UIApplicationMainclass AppDelegate: UIResponder, UIApplicationDelegate, PWMessagingDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { //código de inicialización //establecer delegado personalizado para el manejo de push, en nuestro caso AppDelegate Pushwoosh.configure.delegate = self;
//registrarse para notificaciones push Pushwoosh.configure.registerForPushNotifications()
return true }
//manejar token recibido de APNS func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { Pushwoosh.configure.handlePushRegistration(deviceToken) }
//manejar error al recibir el token func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { Pushwoosh.configure.handlePushRegistrationFailure(error); }
//para notificaciones push silenciosas func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { Pushwoosh.configure.handlePushReceived(userInfo) completionHandler(.noData) }
//este evento se dispara cuando se recibe el push func pushwoosh(_ pushwoosh: Pushwoosh, onMessageReceived message: PWMessage) { print("onMessageReceived: ", message.payload!.description) }
// Se dispara cuando un usuario toca la notificación func pushwoosh(_ pushwoosh: Pushwoosh, onMessageOpened message: PWMessage) { print("onMessageOpened: ", message.payload!.description) }}#import <PushwooshFramework/PushwooshFramework.h>
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { //-----------PARTE DE PUSHWOOSH-----------
// establecer delegado personalizado para el manejo de push, en nuestro caso AppDelegate [Pushwoosh configure].delegate = self;
//¡registrarse para notificaciones push! [[Pushwoosh configure] registerForPushNotifications];
return YES;}
//manejar token recibido de APNS- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { [[Pushwoosh configure] handlePushRegistration:deviceToken];}
//manejar error al recibir el token- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error { [[Pushwoosh configure] handlePushRegistrationFailure:error];}
//para notificaciones push silenciosas- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { [[Pushwoosh configure] handlePushReceived:userInfo]; completionHandler(UIBackgroundFetchResultNoData);}
//este evento se dispara cuando se recibe el push- (void)pushwoosh:(Pushwoosh *)pushwoosh onMessageReceived:(PWMessage *)message { NSLog(@"onMessageReceived: %@", message.payload);}
//este evento se dispara cuando el usuario toca la notificación- (void)pushwoosh:(Pushwoosh *)pushwoosh onMessageOpened:(PWMessage *)message { NSLog(@"onMessageOpened: %@", message.payload);}
@endInfo.plist
Anchor link toEn su Info.plist:
- establezca la clave
Pushwoosh_APPIDen el Código de Aplicación de Pushwoosh. - establezca la clave
Pushwoosh_API_TOKENen el Token de API de Dispositivo de Pushwoosh
4. Seguimiento de la entrega de mensajes
Anchor link toPushwoosh admite el seguimiento de eventos de entrega para notificaciones push a través de la Extensión de Servicio de Notificaciones
Agregar Extensión de Servicio de Notificaciones
Anchor link to- En Xcode, seleccione File > New > Target…
- Elija Notification Service Extension y presione Next.
- Ingrese el nombre del objetivo y presione Finish.
- Cuando se le solicite la activación, presione Cancel.
Dependencias para la Extensión de Servicio de Notificaciones (solo CocoaPods)
Anchor link toNota: Si está utilizando Swift Package Manager para gestionar las dependencias, puede omitir este paso, ya que las dependencias se agregan automáticamente.
Abra su Podfile y agregue la dependencia para el objetivo:
# Descomente la siguiente línea para definir una plataforma global para su proyecto# platform :ios, '9.0'
target 'MyApp' do # Comente la siguiente línea si no quiere usar frameworks dinámicos use_frameworks!
pod 'PushwooshXCFramework'
end
target 'MyAppNotificationExtension' do use_frameworks!
pod 'PushwooshXCFramework'
endEjecute el siguiente comando en la terminal para actualizar las dependencias:
pod updateAgregar el SDK de Pushwoosh a la Extensión de Servicio de Notificaciones
Anchor link toEste código le permite interceptar y procesar notificaciones dentro de su extensión de notificaciones.
import UserNotificationsimport PushwooshFramework
class NotificationService: UNNotificationServiceExtension {
var contentHandler: ((UNNotificationContent) -> Void)? var bestAttemptContent: UNMutableNotificationContent?
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) { // Pushwoosh ********** PWNotificationExtensionManager.shared().handle(request, contentHandler: contentHandler) // ********************
self.contentHandler = contentHandler bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
if let bestAttemptContent = bestAttemptContent { // Modifique el contenido de la notificación aquí... contentHandler(bestAttemptContent) } }
override func serviceExtensionTimeWillExpire() { // Llamado justo antes de que el sistema termine la extensión. // Use esto como una oportunidad para entregar su "mejor intento" de contenido modificado, de lo contrario se usará el payload del push original. if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent { contentHandler(bestAttemptContent) } }
}#import "PWNotificationExtensionManager.h"
@interface NotificationService : UNNotificationServiceExtension
@end
@implementation NotificationService
- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler { // Pushwoosh ********** [[PWNotificationExtensionManager sharedManager] handleNotificationRequest:request contentHandler:contentHandler]; //*********************}
@endInfo.plist
Anchor link toEn el Info.plist de su Extensión de Servicio de Notificaciones, agregue:
Pushwoosh_APPID- Su Código de Aplicación.
5. Ejecutar el proyecto
Anchor link to- Compile y ejecute el proyecto.
- Vaya al Panel de Control de Pushwoosh y envíe una notificación push.
- Debería ver la notificación en la aplicación.
Integración extendida de Pushwoosh para iOS
Anchor link toEn esta etapa, ya ha integrado el SDK y puede enviar y recibir notificaciones push. Ahora, exploremos la funcionalidad principal
Notificaciones push
Anchor link toEn el SDK de Pushwoosh, hay dos callbacks diseñados para manejar notificaciones push:
onMessageReceived: Este método se invoca cuando se recibe una notificación push.onMessageOpened: Este método se llama cuando el usuario interactúa con (abre) la notificación
Estos callbacks permiten a los desarrolladores gestionar la recepción y la interacción del usuario con las notificaciones push dentro de sus aplicaciones
import PushwooshFramework
class AppDelegate: NSObject, UIApplicationDelegate, PWMessagingDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { Pushwoosh.configure.delegate = self; }
func pushwoosh(_ pushwoosh: Pushwoosh, onMessageOpened message: PWMessage) { if let payload = message.payload { print("onMessageOpened: \(payload)") } }
func pushwoosh(_ pushwoosh: Pushwoosh, onMessageReceived message: PWMessage) { if let payload = message.payload { print("onMessageReceived: \(payload)") } }}#import <PushwooshFramework/PushwooshFramework.h>
@interface AppDelegate () <PWMessagingDelegate>
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [[Pushwoosh configure] setDelegate:self]; return YES;}
- (void)pushwoosh:(Pushwoosh *)pushwoosh onMessageOpened:(PWMessage *)message { if (message.payload) { NSLog(@"onMessageOpened: %@", message.payload); }}
- (void)pushwoosh:(Pushwoosh *)pushwoosh onMessageReceived:(PWMessage *)message { if (message.payload) { NSLog(@"onMessageReceived: %@", message.payload); }}@endConfiguración de usuario
Anchor link toAl centrarse en el comportamiento y las preferencias individuales del usuario, puede entregar contenido personalizado, lo que conduce a una mayor satisfacción y lealtad del usuario
import PushwooshFramework
class Registration {
func afterUserLogin(user: User) { let pushwoosh = Pushwoosh.configure // establecer ID de usuario if let userId = user.userId { pushwoosh.setUserId(userId) }
// establecer email de usuario if let userEmail = user.email { pushwoosh.setEmail(userEmail) }
// establecer número de SMS del usuario if let userSmsNumber = user.SmsNumber { pushwoosh.registerSmsNumber(userSmsNumber) }
// establecer número de WhatsApp del usuario if let userWhatsAppNumber = user.WhatsAppNumber { pushwoosh.registerSmsNumber(userWhatsAppNumber) }
// establecer información adicional del usuario como etiquetas para Pushwoosh if let age = user.userDetails.age, let name = user.userDetails.userName, let lastLogin = user.userDetails.lastLoginDate { pushwoosh.setTags([ "age": age, "name": name, "last_login": lastLogin ]) } }}#import <PushwooshFramework/PushwooshFramework.h>
@implementation Registration
- (void)afterUserLogin:(User *)user { Pushwoosh *pushwoosh = [Pushwoosh configure];
// establecer ID de usuario if (user.userId) { [pushwoosh setUserId:user.userId]; }
// establecer email de usuario if (user.email) { [pushwoosh setEmail:user.email]; }
// establecer información adicional del usuario como etiquetas para Pushwoosh if (user.userDetails.age && user.userDetails.userName && user.userDetails.lastLoginDate) { NSDictionary *tags = @{ @"age": user.userDetails.age, @"name": user.userDetails.userName, @"last_login": user.userDetails.lastLoginDate }; [pushwoosh setTags:tags]; }}
@endEtiquetas
Anchor link toLas etiquetas son pares clave-valor asignados a usuarios o dispositivos, lo que permite la segmentación basada en atributos como preferencias o comportamiento, habilitando la mensajería dirigida.
import PushwooshFramework
class UpdateUser { func afterUserUpdateProfile(user: User) { let pushwoosh = Pushwoosh.configure
// establecer lista de categorías favoritas pushwoosh.setTags(["favorite_categories" : user.getFavoriteCategories()])
// establecer información de pago pushwoosh.setTags([ "is_subscribed": user.isSubscribed(), "payment_status": user.getPaymentStatus(), "billing_address": user.getBillingAddress() ]) }}#import <PushwooshFramework/PushwooshFramework.h>
@implementation UpdateUser
- (void)afterUserUpdateProfile:(User *)user { Pushwoosh *pushwoosh = [Pushwoosh configure];
// establecer lista de categorías favoritas [pushwoosh setTags:@{@"favorite_categories" : user.getFavoriteCategories}];
// establecer información de pago NSDictionary *tags = @{ @"is_subscribed": @(user.isSubscribed), @"payment_status": user.getPaymentStatus, @"billing_address": user.getBillingAddress }; [pushwoosh setTags:tags];}
@endEventos
Anchor link toLos eventos son acciones específicas del usuario u ocurrencias dentro de la aplicación que se pueden rastrear para analizar el comportamiento y activar mensajes o acciones correspondientes
import PushwooshFramework
class Registration {
func afterUserLogin(user: User) { if let userName = user.getUserName(), let lastLogin = user.getLastLoginDate() { PWInAppManager.shared().postEvent("login", withAttributes: [ "name": userName, "last_login": lastLogin ]) } }
func afterUserPurchase(user: User, product: Product) { let pushwoosh = Pushwoosh.configure
// Rastrear evento de compra PWInAppManager.shared().postEvent("purchase", withAttributes: [ "product_id": product.getId(), "product_name": product.getName(), "price": product.getPrice(), "quantity": product.getQuantity() ])
// Establecer etiquetas de usuario let lastPurchaseDate = Date().timeIntervalSince1970 let lifetimeSpend = getCurrentLifetimeSpend() + product.getPrice()
pushwoosh.setTags([ "last_purchase_date": lastPurchaseDate, "lifetime_spend": lifetimeSpend ]) }}#import <PushwooshFramework/PushwooshFramework.h>#import <PushwooshFramework/PWInAppManager.h>
@implementation Registration
- (void)afterUserLogin:(User *)user { NSString *userName = [user getUserName]; NSDate *lastLogin = [user getLastLoginDate];
if (userName && lastLogin) { [[PWInAppManager sharedManager] postEvent:@"login" withAttributes:@{ @"name": userName, @"last_login": lastLogin }]; }}
- (void)afterUserPurchase:(User *)user product:(Product *)product { Pushwoosh *pushwoosh = [Pushwoosh configure];
// Rastrear evento de compra [[PWInAppManager sharedManager] postEvent:@"purchase" withAttributes:@{ @"product_id": [product getId], @"product_name": [product getName], @"price": @([product getPrice]), @"quantity": @([product getQuantity]) }];
// Establecer etiquetas de usuario NSTimeInterval lastPurchaseDate = [[NSDate date] timeIntervalSince1970]; double lifetimeSpend = /* obtener el gasto total actual */ + [product getPrice];
NSDictionary *tags = @{ @"last_purchase_date": @(lastPurchaseDate), @"lifetime_spend": @(lifetimeSpend) };
[pushwoosh setTags:tags];}
@endRich Media
Anchor link toRich media se refiere a contenido interactivo y multimedia, como imágenes, videos o HTML, utilizado en notificaciones y mensajes in-app para mejorar la participación del usuario
import PushwooshFramework
class ViewController: UIViewController, PWRichMediaPresentingDelegate {
override func viewDidLoad() { super.viewDidLoad() let richMediaConfiguration = PWModalWindowConfiguration.shared()
PWRichMediaManager.shared().delegate = self richMediaConfiguration.configureModalWindow(with: .PWModalWindowPositionBottom, present: .PWAnimationPresentFromBottom, dismiss: .PWAnimationDismissDown) }
func richMediaManager(_ richMediaManager: PWRichMediaManager!, shouldPresent richMedia: PWRichMedia!) -> Bool { print("Rich media will be presented with: \(richMedia.pushPayload!)") return true }
func richMediaManager(_ richMediaManager: PWRichMediaManager!, didPresent richMedia: PWRichMedia!) { print("Rich media has been presented with: \(richMedia.pushPayload!)") }
func richMediaManager(_ richMediaManager: PWRichMediaManager!, didClose richMedia: PWRichMedia!) { print("Rich media has been closed with: \(richMedia.pushPayload!)") }
func richMediaManager(_ richMediaManager: PWRichMediaManager!, presentingDidFailFor richMedia: PWRichMedia!, withError error: (any Error)!) { print("Failed to present rich media with: \(richMedia.pushPayload!). Error: \(error.localizedDescription)") }}#import "ViewController.h"#import <PushwooshFramework/PushwooshFramework.h>#import <PushwooshFramework/PWRichMediaManager.h>#import <PushwooshFramework/PWModalWindowConfiguration.h>
@interface ViewController () <PWRichMediaPresentingDelegate>
@end
@implementation ViewController
- (void)viewDidLoad { [super viewDidLoad];
[[PWRichMediaManager sharedManager] setDelegate:self]; [[PWModalWindowConfiguration shared] configureModalWindowWith:PWModalWindowPositionBottom presentAnimation:PWAnimationPresentFromBottom dismissAnimation:PWAnimationDismissDown];}
- (BOOL)richMediaManager:(PWRichMediaManager *)richMediaManager shouldPresentRichMedia:(PWRichMedia *)richMedia { NSLog(@"Rich media will be presented with: %@", richMedia.pushPayload); return YES;}
- (void)richMediaManager:(PWRichMediaManager *)richMediaManager didPresentRichMedia:(PWRichMedia *)richMedia { NSLog(@"Rich media has been presented with: %@", richMedia.pushPayload);}
- (void)richMediaManager:(PWRichMediaManager *)richMediaManager didCloseRichMedia:(PWRichMedia *)richMedia { NSLog(@"Rich media has been closed with:: %@", richMedia.pushPayload);}
- (void)richMediaManager:(PWRichMediaManager *)richMediaManager presentingDidFailForRichMedia:(PWRichMedia *)richMedia withError:(NSError *)error { NSLog(@"Failed to present rich media with: %@. Error: %@", richMedia.pushPayload, error.localizedDescription);}
@endSolución de problemas
Anchor link toError al compilar el módulo ‘PushwooshFramework’
Anchor link toAl compilar su proyecto, puede encontrar un error similar a:
Failed to build module 'PushwooshFramework'; this SDK is not supported by the compiler(the SDK is built with 'Apple Swift version 5.10 (swiftlang-5.10.0.13 clang-1500.3.9.4)',while this compiler is 'Apple Swift version 6.1.2 effective-5.10 (swiftlang-6.1.2.1.2 clang-1700.0.13.5)')Causa: Este error no está relacionado con la incompatibilidad de la versión del compilador de Swift. A partir de la versión 6.8.0 del SDK de iOS de Pushwoosh, el SDK está modularizado en varios componentes que interactúan entre sí. El error ocurre cuando no se agregan todos los frameworks requeridos a su proyecto.
Solución: Asegúrese de que los cuatro frameworks requeridos se agreguen a su objetivo de aplicación al integrar a través de Swift Package Manager:
PushwooshFrameworkPushwooshCorePushwooshBridgePushwooshLiveActivities

Para verificar esto en Xcode:
- Seleccione su proyecto en el Navegador de Proyectos
- Seleccione el objetivo de su aplicación
- Vaya a General > Frameworks, Libraries, and Embedded Content
- Confirme que los cuatro frameworks están en la lista
Si encuentra algún problema durante el proceso de integración, consulte la sección de soporte y comunidad.