Pular para o conteúdo

Guia de integração básica do SDK para iOS

Esta seção contém informações sobre como integrar o SDK da Pushwoosh em seu aplicativo iOS.

Pré-requisitos

Anchor link to

Para integrar o SDK da Pushwoosh para iOS em seu aplicativo, você precisará do seguinte:

Passos de integração

Anchor link to

1. Instalação

Anchor link to

Você pode integrar o SDK da Pushwoosh em seu aplicativo usando o Swift Package Manager ou o CocoaPods.

Swift Package Manager

Anchor link to

Na seção Package Dependencies, adicione o seguinte pacote:

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

Para usar o SDK da Pushwoosh para iOS, certifique-se de adicionar os quatro frameworks a seguir ao seu target do aplicativo ao integrar via Swift Package Manager:

  • PushwooshFramework
  • PushwooshCore
  • PushwooshBridge
  • PushwooshLiveActivities

Abra seu Podfile e adicione a dependência:

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

Em seguida, no terminal, execute o seguinte comando para instalar as dependências:

Terminal window
pod install

2. Capabilities

Anchor link to

Para habilitar as Notificações Push em seu projeto, você precisa adicionar certas capacidades.

Na seção Signing & Capabilities, adicione as seguintes capacidades:

  • Push Notifications
  • Background Modes. Após adicionar esta capacidade, marque a caixa para Remote notifications.

Se você pretende usar Notificações Sensíveis ao Tempo (iOS 15+), adicione também a capacidade Time Sensitive Notifications.

3. Código de inicialização

Anchor link to

AppDelegate

Anchor link to

Adicione o seguinte código à sua classe 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

No seu Info.plist:

4. Rastreamento de entrega de mensagens

Anchor link to

O Pushwoosh suporta o rastreamento de eventos de entrega para notificações push através da Notification Service Extension

Adicionar Notification Service Extension

Anchor link to
  1. No Xcode, selecione File > New > Target…
  2. Escolha Notification Service Extension e pressione Next.
  3. Digite o nome do target e pressione Finish.
  4. Quando solicitado para ativação, pressione Cancel.

Dependências para a Notification Service Extension (apenas CocoaPods)

Anchor link to

Nota: Se você estiver usando o Swift Package Manager para gerenciar dependências, pode pular esta etapa, pois as dependências são adicionadas automaticamente.

Abra seu Podfile e adicione a dependência para o 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

Execute o seguinte comando no terminal para atualizar as dependências:

Terminal window
pod update

Adicionar o SDK da Pushwoosh à Notification Service Extension

Anchor link to

Este código permite que você intercepte e processe notificações dentro da sua extensão de notificação.

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

No Info.plist da sua Notification Service Extension, adicione:

  • Pushwoosh_APPID - O seu Código de Aplicação.

5. Execute o projeto

Anchor link to
  1. Compile e execute o projeto.
  2. Vá para o Painel de Controle da Pushwoosh e envie uma notificação push.
  3. Você deve ver a notificação no aplicativo.

Integração estendida do Pushwoosh para iOS

Anchor link to

Neste ponto, você já integrou o SDK e pode enviar e receber notificações push. Agora, vamos explorar a funcionalidade principal

Notificações push

Anchor link to

No SDK da Pushwoosh, existem dois callbacks projetados para lidar com notificações push:

  • onMessageReceived: Este método é invocado quando uma notificação push é recebida.
  • onMessageOpened: Este método é chamado quando o usuário interage com (abre) a notificação

Esses callbacks permitem que os desenvolvedores gerenciem o recebimento e a interação do usuário com as notificações push em seus aplicativos

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

Configuração do usuário

Anchor link to

Ao focar no comportamento e nas preferências individuais do usuário, você pode entregar conteúdo personalizado, levando a um aumento da satisfação e lealdade do usuário

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
])
}
}
}

Tags são pares de chave-valor atribuídos a usuários ou dispositivos, permitindo a segmentação com base em atributos como preferências ou comportamento, possibilitando o envio de mensagens direcionadas.

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()
])
}
}

Eventos são ações ou ocorrências específicas do usuário dentro do aplicativo que podem ser rastreadas para analisar o comportamento e acionar mensagens ou ações correspondentes

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 refere-se a conteúdo interativo e multimídia, como imagens, vídeos ou HTML, usado em notificações e mensagens in-app para aumentar o engajamento do usuário

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

Solução de problemas

Anchor link to

Falha ao compilar o módulo ‘PushwooshFramework’

Anchor link to

Ao compilar seu projeto, você pode encontrar um erro semelhante 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 erro não está relacionado à incompatibilidade da versão do compilador Swift. A partir da versão 6.8.0 do SDK da Pushwoosh para iOS, o SDK é modularizado em vários componentes que interagem entre si. O erro ocorre quando nem todos os frameworks necessários são adicionados ao seu projeto.

Solução: Certifique-se de que todos os quatro frameworks necessários sejam adicionados ao seu target do aplicativo ao integrar via Swift Package Manager:

  • PushwooshFramework
  • PushwooshCore
  • PushwooshBridge
  • PushwooshLiveActivities

Para verificar isso no Xcode:

  1. Selecione seu projeto no Project Navigator
  2. Selecione o target do seu aplicativo
  3. Vá para General > Frameworks, Libraries, and Embedded Content
  4. Confirme que todos os quatro frameworks estão listados

Se você encontrar algum problema durante o processo de integração, consulte a seção de suporte e comunidade.