Guía de integración básica del SDK de iOS
Esta sección contiene información sobre cómo integrar el SDK de Pushwoosh en su aplicación iOS.
Prerrequisitos
Anchor link toPara integrar el SDK de Pushwoosh para iOS 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, añada el siguiente paquete:
https://github.com/Pushwoosh/Pushwoosh-XCFrameworkPara usar el SDK de Pushwoosh para iOS, asegúrese de añadir los siguientes cuatro frameworks a su app target al integrar a través de Swift Package Manager:
PushwooshFrameworkPushwooshCorePushwooshBridgePushwooshLiveActivities

CocoaPods
Anchor link toAbra su Podfile y añada la dependencia:
# Descomenta la siguiente línea para definir una plataforma global para tu proyecto# platform :ios, '9.0'
target 'MyApp' do # Comenta la siguiente línea si no quieres 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 añadir ciertas capacidades.
En la sección Signing & Capabilities, añada las siguientes capacidades:
Push NotificationsBackground Modes. Después de añadir esta capacidad, marque la casilla paraRemote notifications.
Si tiene la intención de usar Notificaciones Sensibles al Tiempo (iOS 15+), añada también la capacidad Time Sensitive Notifications.
3. Código de inicialización
Anchor link toAppDelegate
Anchor link toAñada 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.sharedInstance().delegate = self
// Registrarse para notificaciones push Pushwoosh.sharedInstance().registerForPushNotifications()
return true }
// Manejar token recibido de APNS func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { Pushwoosh.sharedInstance().handlePushRegistration(deviceToken) }
// Manejar error al recibir el token func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { Pushwoosh.sharedInstance().handlePushRegistrationFailure(error) }
//para notificaciones push silenciosas func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { Pushwoosh.sharedInstance().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.sharedInstance().delegate = self;
//registrarse para notificaciones push Pushwoosh.sharedInstance().registerForPushNotifications()
return true }
//manejar token recibido de APNS func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { Pushwoosh.sharedInstance().handlePushRegistration(deviceToken) }
//manejar error al recibir el token func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { Pushwoosh.sharedInstance().handlePushRegistrationFailure(error); }
//para notificaciones push silenciosas func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { Pushwoosh.sharedInstance().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 sharedInstance].delegate = self;
//¡registrarse para notificaciones push! [[Pushwoosh sharedInstance] registerForPushNotifications];
return YES;}
//manejar token recibido de APNS- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { [[Pushwoosh sharedInstance] handlePushRegistration:deviceToken];}
//manejar error al recibir el token- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error { [[Pushwoosh sharedInstance] handlePushRegistrationFailure:error];}
//para notificaciones push silenciosas- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { [[Pushwoosh sharedInstance] 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_APPIDcon el Código de Aplicación de Pushwoosh. - establezca la clave
Pushwoosh_API_TOKENcon el Token de API de Dispositivo de Pushwoosh
4. Seguimiento de la entrega de mensajes
Anchor link toPushwoosh soporta el seguimiento de eventos de entrega para notificaciones push a través de la Extensión de Servicio de Notificación
Añadir Extensión de Servicio de Notificación
Anchor link to- En Xcode, seleccione File > New > Target…
- Elija Notification Service Extension y presione Next.
- Ingrese el nombre del target y presione Finish.
- Cuando se le pida la activación, presione Cancel.
Dependencias para la Extensión de Servicio de Notificación (solo CocoaPods)
Anchor link toNota: Si está utilizando Swift Package Manager para gestionar las dependencias, puede omitir este paso, ya que las dependencias se añaden automáticamente.
Abra su Podfile y añada la dependencia para el target:
# Descomenta la siguiente línea para definir una plataforma global para tu proyecto# platform :ios, '9.0'
target 'MyApp' do # Comenta la siguiente línea si no quieres 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 updateAñadir el SDK de Pushwoosh a la Extensión de Servicio de Notificación
Anchor link toEste código le permite interceptar y procesar notificaciones dentro de su extensión de notificación.
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 { // Modifica el contenido de la notificación aquí... contentHandler(bestAttemptContent) } }
override func serviceExtensionTimeWillExpire() { // Se llama justo antes de que el sistema termine la extensión. // Usa esto como una oportunidad para entregar tu "mejor intento" de contenido modificado, de lo contrario se usará el payload original del push. 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 Notificación, añada:
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 este punto, 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.sharedInstance().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 sharedInstance] 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 de los usuarios, puede ofrecer 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.sharedInstance() // 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 de usuario if let userSmsNumber = user.SmsNumber { pushwoosh.registerSmsNumber(userSmsNumber) }
// establecer número de WhatsApp de usuario if let userWhatsAppNumber = user.WhatsAppNumber { pushwoosh.registerSmsNumber(userWhatsAppNumber) }
// establecer información adicional del usuario como tags 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 sharedInstance];
// 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 tags 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]; }}
@endTags
Anchor link toLos Tags son pares clave-valor asignados a usuarios o dispositivos, que permiten 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.sharedInstance()
// 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 sharedInstance];
// 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 pueden ser rastreadas para analizar el comportamiento y desencadenar 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.sharedInstance()
// Rastrear evento de compra PWInAppManager.shared().postEvent("purchase", withAttributes: [ "product_id": product.getId(), "product_name": product.getName(), "price": product.getPrice(), "quantity": product.getQuantity() ])
// Establecer tags 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 sharedInstance];
// Rastrear evento de compra [[PWInAppManager sharedManager] postEvent:@"purchase" withAttributes:@{ @"product_id": [product getId], @"product_name": [product getName], @"price": @([product getPrice]), @"quantity": @([product getQuantity]) }];
// Establecer tags 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 construir 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 Pushwoosh para iOS, el SDK está modularizado en varios componentes que interactúan entre sí. El error ocurre cuando no todos los frameworks requeridos se añaden a su proyecto.
Solución: Asegúrese de que los cuatro frameworks requeridos se añaden a su app target al integrar a través de Swift Package Manager:
PushwooshFrameworkPushwooshCorePushwooshBridgePushwooshLiveActivities

Para verificar esto en Xcode:
- Seleccione su proyecto en el Navegador de Proyectos
- Seleccione su app target
- 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, por favor consulte la sección de soporte y comunidad.