Saltar al contenido

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 de iOS.

Prerrequisitos

Anchor link to

Para integrar el SDK de Pushwoosh para iOS en su aplicación, necesitará lo siguiente:

Pasos de integración

Anchor link to

1. Instalación

Anchor link to

Puede integrar el SDK de Pushwoosh en su aplicación utilizando Swift Package Manager o CocoaPods.

Swift Package Manager

Anchor link to

En la sección Package Dependencies, agregue el siguiente paquete:

https://github.com/Pushwoosh/Pushwoosh-XCFramework

Para usar el SDK de Pushwoosh para iOS, asegúrese de agregar los siguientes cuatro frameworks a su app target al integrar a través de Swift Package Manager:

  • PushwooshFramework
  • PushwooshCore
  • PushwooshBridge
  • PushwooshLiveActivities

Abra su Podfile y agregue la dependencia:

Terminal window
# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'
target 'MyApp' do
# Comment the next line if you don't want to use dynamic frameworks
use_frameworks!
pod 'PushwooshXCFramework'
end

Luego, en la terminal, ejecute el siguiente comando para instalar las dependencias:

Terminal window
pod install

2. Capacidades

Anchor link to

Para habilitar las Notificaciones Push en su proyecto, necesita agregar ciertas capacidades.

En la sección Signing & Capabilities, agregue las siguientes capacidades:

  • Push Notifications
  • Background Modes. Después de agregar esta capacidad, marque la casilla para Remote notifications.

Si tiene la intención de usar Time Sensitive Notifications (iOS 15+), agregue también la capacidad de Time Sensitive Notifications.

3. Código de inicialización

Anchor link to

AppDelegate

Anchor link to

Agregue el siguiente código a su clase AppDelegate:

import SwiftUI
import PushwooshFramework
@main
struct MyApp: App {
// Register AppDelegate as 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 {
// Initialization code
// Set custom delegate for push handling
Pushwoosh.sharedInstance().delegate = self
// Register for push notifications
Pushwoosh.sharedInstance().registerForPushNotifications()
return true
}
// Handle token received from APNS
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Pushwoosh.sharedInstance().handlePushRegistration(deviceToken)
}
// Handle token receiving error
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
Pushwoosh.sharedInstance().handlePushRegistrationFailure(error)
}
//for silent push notifications
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
Pushwoosh.sharedInstance().handlePushReceived(userInfo)
completionHandler(.noData)
}
// Fired when a push is received
func pushwoosh(_ pushwoosh: Pushwoosh, onMessageReceived message: PWMessage) {
print("onMessageReceived: ", message.payload!.description)
}
// Fired when a user taps the notification
func pushwoosh(_ pushwoosh: Pushwoosh, onMessageOpened message: PWMessage) {
print("onMessageOpened: ", message.payload!.description)
}
}
struct ContentView: View {
var body: some View {
Text("Pushwoosh with SwiftUI")
.padding()
}
}

Info.plist

Anchor link to

En su Info.plist:

4. Seguimiento de la entrega de mensajes

Anchor link to

Pushwoosh admite el seguimiento de eventos de entrega para notificaciones push a través de la Notification Service Extension

Agregar Notification Service Extension

Anchor link to
  1. En Xcode, seleccione File > New > Target…
  2. Elija Notification Service Extension y presione Next.
  3. Ingrese el nombre del target y presione Finish.
  4. Cuando se le solicite la activación, presione Cancel.

Dependencias para la Notification Service Extension (solo CocoaPods)

Anchor link to

Nota: 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 target:

Podfile
# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'
target 'MyApp' do
# Comment the next line if you don't want to use dynamic frameworks
use_frameworks!
pod 'PushwooshXCFramework'
end
target 'MyAppNotificationExtension' do
use_frameworks!
pod 'PushwooshXCFramework'
end

Ejecute el siguiente comando en la terminal para actualizar las dependencias:

Terminal window
pod update

Agregar el SDK de Pushwoosh a la Notification Service Extension

Anchor link to

Este código le permite interceptar y procesar notificaciones dentro de su extensión de notificación.

import UserNotifications
import 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 {
// Modify the notification content here...
contentHandler(bestAttemptContent)
}
}
override func serviceExtensionTimeWillExpire() {
// Called just before the extension will be terminated by the system.
// Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent {
contentHandler(bestAttemptContent)
}
}
}

Info.plist

Anchor link to

En el Info.plist de su Notification Service Extension, agregue:

  • Pushwoosh_APPID - Su Código de Aplicación.

5. Ejecutar el proyecto

Anchor link to
  1. Compile y ejecute el proyecto.
  2. Vaya al Panel de Control de Pushwoosh y envíe una notificación push.
  3. Debería ver la notificación en la aplicación.

Integración extendida de Pushwoosh para iOS

Anchor link to

En esta etapa, ya ha integrado el SDK y puede enviar y recibir notificaciones push. Ahora, exploremos la funcionalidad principal

Notificaciones push

Anchor link to

En 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)")
}
}
}

Configuración de usuario

Anchor link to

Al 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()
// set user ID
if let userId = user.userId {
pushwoosh.setUserId(userId)
}
// set user email
if let userEmail = user.email {
pushwoosh.setEmail(userEmail)
}
// set user SMS number
if let userSmsNumber = user.SmsNumber {
pushwoosh.registerSmsNumber(userSmsNumber)
}
// set user WhatsApp number
if let userWhatsAppNumber = user.WhatsAppNumber {
pushwoosh.registerSmsNumber(userWhatsAppNumber)
}
// setting additional user information as tags for 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
])
}
}
}

Las etiquetas son pares clave-valor asignados a usuarios o dispositivos, que permiten la segmentación basada en atributos como preferencias o comportamiento, lo que posibilita la mensajería dirigida.

import PushwooshFramework
class UpdateUser {
func afterUserUpdateProfile(user: User) {
let pushwoosh = Pushwoosh.sharedInstance()
// set list of favorite categories
pushwoosh.setTags(["favorite_categories" : user.getFavoriteCategories()])
// set payment information
pushwoosh.setTags([
"is_subscribed": user.isSubscribed(),
"payment_status": user.getPaymentStatus(),
"billing_address": user.getBillingAddress()
])
}
}

Los eventos son acciones específicas del usuario u ocurrencias dentro de la aplicación que se pueden rastrear para analizar el comportamiento y activar los 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()
// Track purchase event
PWInAppManager.shared().postEvent("purchase", withAttributes: [
"product_id": product.getId(),
"product_name": product.getName(),
"price": product.getPrice(),
"quantity": product.getQuantity()
])
// Set user tags
let lastPurchaseDate = Date().timeIntervalSince1970
let lifetimeSpend = getCurrentLifetimeSpend() + product.getPrice()
pushwoosh.setTags([
"last_purchase_date": lastPurchaseDate,
"lifetime_spend": lifetimeSpend
])
}
}

Rich Media

Anchor link to

Rich 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)")
}
}

Solución de problemas

Anchor link to

Error al compilar el módulo ‘PushwooshFramework’

Anchor link to

Al 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 se agregan todos los frameworks requeridos a su proyecto.

Solución: Asegúrese de que los cuatro frameworks requeridos se agreguen a su app target al integrar a través de Swift Package Manager:

  • PushwooshFramework
  • PushwooshCore
  • PushwooshBridge
  • PushwooshLiveActivities

Para verificar esto en Xcode:

  1. Seleccione su proyecto en el Project Navigator
  2. Seleccione su app target
  3. Vaya a General > Frameworks, Libraries, and Embedded Content
  4. 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.