Saltar al contenido

iOS SDK 7.0+ 基本集成指南

Este contenido aún no está disponible en su idioma.

本节包含有关如何将 Pushwoosh SDK 集成到您的 iOS 应用程序中的信息。

先决条件

Anchor link to

要将 Pushwoosh iOS SDK 集成到您的应用程序中,您需要满足以下先决条件:

集成步骤

Anchor link to

您可以使用 Swift Package ManagerCocoaPods 将 Pushwoosh SDK 集成到您的应用程序中。

Swift Package Manager

Anchor link to

Package Dependencies 部分,添加以下包:

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

要使用 Pushwoosh iOS SDK,请确保在通过 Swift Package Manager 集成时将以下四个框架添加到您的应用程序目标中:

  • PushwooshFramework
  • PushwooshCore
  • PushwooshBridge
  • PushwooshLiveActivities

打开您的 Podfile 并添加依赖项:

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

然后,在终端中运行以下命令来安装依赖项:

Terminal window
pod install

2. 功能 (Capabilities)

Anchor link to

要在您的项目中启用推送通知,您需要添加某些功能。

在 Signing & Capabilities 部分,添加以下功能:

  • Push Notifications
  • Background Modes。添加此功能后,选中 Remote notifications 复选框。

如果您打算使用 Time Sensitive Notifications (iOS 15+),也请添加 Time Sensitive Notifications 功能。

3. 初始化代码

Anchor link to

AppDelegate

Anchor link to

将以下代码添加到您的 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.configure.delegate = self
// Register for push notifications
Pushwoosh.configure.registerForPushNotifications()
return true
}
// Handle token received from APNS
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
Pushwoosh.configure.handlePushRegistration(deviceToken)
}
// Handle token receiving error
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
Pushwoosh.configure.handlePushRegistrationFailure(error)
}
//for silent push notifications
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
Pushwoosh.configure.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

在您的 Info.plist 中:

4. 消息送达跟踪

Anchor link to

Pushwoosh 支持通过 Notification Service Extension 跟踪推送通知的送达事件。

添加 Notification Service Extension

Anchor link to
  1. 在 Xcode 中,选择 File > New > Target…
  2. 选择 Notification Service Extension 并按 Next
  3. 输入目标名称并按 Finish
  4. 当提示激活时,按 Cancel

Notification Service Extension 的依赖项 (仅限 CocoaPods)

Anchor link to

注意:如果您使用 Swift Package Manager 管理依赖项,则可以跳过此步骤,因为依赖项会自动添加。

打开您的 Podfile 并为目标添加依赖项:

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

在终端中运行以下命令以更新依赖项:

Terminal window
pod update

将 Pushwoosh SDK 添加到 Notification Service Extension

Anchor link to

此代码允许您在通知扩展中拦截和处理通知。

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

在您的 Notification Service Extension 的 Info.plist 中,添加:

  • Pushwoosh_APPID - 您的 Application Code。

5. 运行项目

Anchor link to
  1. 构建并运行项目。
  2. 前往 Pushwoosh 控制面板并发送推送通知
  3. 您应该会在应用程序中看到该通知。

扩展 Pushwoosh iOS 集成

Anchor link to

至此,您已经集成了 SDK,可以发送和接收推送通知。现在,让我们来探索核心功能。

推送通知

Anchor link to

在 Pushwoosh SDK 中,有两个用于处理推送通知的回调:

  • onMessageReceived:当收到推送通知时调用此方法。
  • onMessageOpened:当用户与通知交互(打开)时调用此方法。

这些回调使开发人员能够在其应用程序中管理推送通知的接收和用户交互。

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

用户配置

Anchor link to

通过关注个人用户的行为和偏好,您可以提供个性化的内容,从而提高用户满意度和忠诚度。

import PushwooshFramework
class Registration {
func afterUserLogin(user: User) {
let pushwoosh = Pushwoosh.configure
// 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)

Anchor link to

标签是分配给用户或设备的键值对,允许根据偏好或行为等属性进行分段,从而实现有针对性的消息传递。

import PushwooshFramework
class UpdateUser {
func afterUserUpdateProfile(user: User) {
let pushwoosh = Pushwoosh.configure
// 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()
])
}
}

事件 (Events)

Anchor link to

事件是应用程序内可以跟踪的特定用户操作或事件,用于分析行为并触发相应的消息或操作。

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
// 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

富媒体是指通知和应用内消息中使用的交互式多媒体内容,例如图像、视频或 HTML,以增强用户参与度。

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

故障排除

Anchor link to

Failed to build module ‘PushwooshFramework’

Anchor link to

构建项目时,您可能会遇到类似以下的错误:

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)')

原因: 此错误与 Swift 编译器版本不兼容无关。从 Pushwoosh iOS SDK 6.8.0 版本开始,SDK 被模块化为多个相互交互的组件。当并非所有必需的框架都添加到您的项目中时,就会发生此错误。

解决方案: 确保在通过 Swift Package Manager 集成时将所有四个必需的框架都添加到您的应用程序目标中:

  • PushwooshFramework
  • PushwooshCore
  • PushwooshBridge
  • PushwooshLiveActivities

要在 Xcode 中验证这一点:

  1. 在 Project Navigator 中选择您的项目
  2. 选择您的应用程序目标
  3. 前往 General > Frameworks, Libraries, and Embedded Content
  4. 确认所有四个框架都已列出

如果您在集成过程中遇到任何问题,请参阅支持和社区部分。