Klaviyo Swift SDK 允许开发者将 Klaviyo 的分析和推送通知功能集成到他们的 iOS 应用程序中。该 SDK 协助通过 Klaviyo Client APIs 识别用户和追踪事件。为了减少性能开销,API 请求会被排队并批量发送。队列会被持久化到本地存储,以便在设备离线或应用程序终止时数据不会丢失。
集成后,您的营销团队将能够更好地了解您的应用程序用户的需求,并通过 APNs 向他们发送及时的消息。
在您的 Xcode 项目中启用推送通知功能。此 Apple 开发者指南中的“启用推送通知功能”部分提供了详细的说明。
如果您打算使用 富媒体推送通知或 自定义角标计数,请将 Notification Service Extension 添加到您的 Xcode 项目。Notification Service Extension 作为独立的包在您的 iOS 应用程序内部发布。要将此扩展添加到您的应用程序:
⚠️ 您的通知服务扩展的部署目标默认为最新的 iOS 版本。如果这超过了您的应用程序支持的最低 iOS 版本,推送通知可能无法在较旧的设备上显示附加的媒体。为避免这种情况,请确保扩展的最低部署目标与您的应用程序的最低部署目标相匹配。⚠️
在您的主应用程序目标和您的 Notification Service Extension 之间设置一个 App Group。
group.com.[MainTargetBundleId].[descriptor]
创建一个新的 App GroupInfo.plist
中,为 klaviyo_app_group
添加一个新的条目,类型为 String,值为 App Group 名称Info.plist
中,为 klaviyo_app_group
添加一个新的条目,类型为 String,值为 App Group 名称根据您使用的依赖管理工具,按照以下说明安装 Klaviyo 的依赖项。
KlaviyoSwift 可以通过 Swift Package Manager 获得。按照以下步骤进行安装。
https://github.com/klaviyo/klaviyo-swift-sdk
。这应该会在屏幕上显示该软件包。KlaviyoSwift
分配给您的应用程序目标,并将 KlaviyoSwiftExtension
分配给通知服务扩展目标(如果已创建),然后单击“Add Package”。KlaviyoSwift 可通过 CocoaPods 获得。
YourAppTarget
和 YourAppNotificationServiceExtenionTarget
替换为您的应用程序和通知服务扩展目标的名称。target 'YourAppTarget' do
pod 'KlaviyoSwift'
end
target 'YourAppNotificationServiceExtenionTarget' do
pod 'KlaviyoSwiftExtension'
end
pod install
以完成集成。可以通过 pod update KlaviyoSwift
和 pod update KlaviyoSwiftExtension
保持库为最新状态。最后,在 NotificationService.swift
文件中,从 此文件中添加两个所需的代理。此示例涵盖调用 Klaviyo,以便我们可以下载媒体并将其附加到推送通知,以及处理自定义角标计数。
SDK 必须使用您的 Klaviyo 帐户的短字母数字 公共 API 密钥(也称为您的站点 ID)进行初始化。
// AppDelegate
import KlaviyoSwift
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
KlaviyoSDK().initialize(with: "YOUR_KLAVIYO_PUBLIC_API_KEY")
return true
}
}
SDK 应该在调用任何其他 Klaviyo SDK 方法之前初始化。
SDK 提供了通过 Create Client Profile API 将您的用户识别为 Klaviyo 用户的方法。可以通过以下任意组合来识别用户:
以上标识符会被持久化到本地存储,以便 SDK 可以在您发出事件请求或想要设置推送令牌等时,跟踪当前用户/用户。
可以一次性设置或单独设置用户标识符。无论哪种方式,SDK 都会对 API 调用进行分组和批量处理,以提高性能。
以下代码演示了如何设置用户标识符:
// organization, title, image, location and additional properties (dictionary) can also be set using the below constructor
let profile = Profile(email: "junior@blob.com", firstName: "Blob", lastName: "Jr.")
KlaviyoSDK().set(profile: profile)
// or setting individual properties
KlaviyoSDK().set(profileAttribute: .firstName, value: "Blob")
KlaviyoSDK().set(profileAttribute: .lastName, value: "Jr.")
要完全启动一个新用户(例如,如果用户注销),请调用 KlaviyoSDK().resetProfile()
以清除当前跟踪的用户标识符,或使用 KlaviyoSDK().set(profile: profile)
以使用新的用户对象覆盖它。
// start a profile for Blob Jr.
let profile = Profile(email: "junior@blob.com", firstName: "Blob", lastName: "Jr.")
KlaviyoSDK().set(profile: profile)
// stop tracking Blob Jr.
KlaviyoSDK().resetProfile()
// start a profile for Robin Hood
let profile = Profile(email: "robin@hood.com", firstName: "Robin", lastName: "Hood")
KlaviyoSDK().set(profile: profile)
每当设置推送令牌或创建事件时,Klaviyo 将使用自动生成的 ID 跟踪未识别的用户。 这样,您可以在收集电子邮件或电话号码等用户标识符之前收集推送令牌和跟踪事件。 当提供标识符时,Klaviyo 会将匿名用户与已识别用户合并。
SDK 提供了用于通过 Create Client Event API 跟踪用户在您的应用程序上执行的事件的工具。 以下是有关如何跟踪事件的示例:
// using a predefined event name
let event = Event(name: .StartedCheckoutMetric,
properties: [
"name": "cool t-shirt",
"color": "blue",
"size": "medium",
],
value: 166 )
KlaviyoSDK().create(event: event)
// using a custom event name
let customEvent = Event(name: .CustomEvent("Checkout Completed"),
properties: [
"name": "cool t-shirt",
"color": "blue",
"size": "medium",
],
value: 166)
KlaviyoSDK().create(event: customEvent)
create
方法将事件对象作为参数。 可以使用以下参数构造事件:
name
:您要跟踪的事件的名称,作为 EventName
枚举。可以在 Event.EventName
中找到 Klaviyo 定义的常见事件指标列表。您还可以使用 Event.EventName
的 CustomEvent
枚举案例创建自定义事件properties
:特定于该事件的属性的字典。 此参数是可选的。value
:与此事件关联的数值(Double
)。例如,购买的美元金额。为了向您的用户发送推送通知,您必须收集他们的推送令牌并向 Klaviyo 注册它们。 这是通过 KlaviyoSDK().set(pushToken:)
方法完成的,该方法通过 Create Client Push Token API 注册推送令牌和当前授权状态。
registerForRemoteNotifications()
以从 APNs 请求推送令牌。 这通常在应用程序委托的 application:didFinishLaunchingWithOptions:
方法中完成。application:didRegisterForRemoteNotificationsWithDeviceToken
以从 APNs 接收推送令牌并向 Klaviyo 注册它。以下是执行上述两个步骤的代码
import KlaviyoSwift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
KlaviyoSDK().initialize(with: "YOUR_KLAVIYO_PUBLIC_API_KEY")
UIApplication.shared.registerForRemoteNotifications()
return true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
KlaviyoSDK().set(pushToken: deviceToken)
}
获取推送令牌后,下一步是请求用户授权发送推送通知。 您可以在应用程序中的任何位置添加权限请求代码,以便提示用户请求此权限。 Apple 提供了一些关于何时以及如何请求此权限的最佳实践 指南。 以下示例演示了如何在应用程序委托文件中的 application:didFinishLaunchingWithOptions:
方法中请求推送权限。 但是,值得注意的是,这可能不是理想的位置,因为它可能会中断应用程序的启动体验。
设置推送令牌后,每当应用程序打开或从后台恢复时,Klaviyo SDK 将自动跟踪用户通知权限的更改。
以下是请求推送通知权限的示例代码
import UserNotifications
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
KlaviyoSDK().initialize(with: "YOUR_KLAVIYO_PUBLIC_API_KEY")
UIApplication.shared.registerForRemoteNotifications()
let center = UNUserNotificationCenter.current()
center.delegate = self as? UNUserNotificationCenterDelegate // the type casting can be removed once the delegate has been implemented
let options: UNAuthorizationOptions = [.alert, .sound, .badge]
// use the below options if you are interested in using provisional push notifications. Note that using this will not
// show the push notifications prompt to the user.
// let options: UNAuthorizationOptions = [.alert, .sound, .badge, .provisional]
center.requestAuthorization(options: options) { granted, error in
if let error = error {
// Handle the error here.
print("error = ", error)
}
// Irrespective of the authorization status call `registerForRemoteNotifications` here so that
// the `didRegisterForRemoteNotificationsWithDeviceToken` delegate is called. Doing this
// will make sure that Klaviyo always has the latest push authorization status.
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
return true
}
当用户点击推送通知时,在您的应用程序委托中实现 userNotificationCenter:didReceive:withCompletionHandler
和 userNotificationCenter:willPresent:withCompletionHandler
,以分别处理在应用程序处于后台和前台时接收推送通知。
以下是如何在您的应用程序委托中处理推送通知的示例
// be sure to set the UNUserNotificationCenterDelegate to self in the didFinishLaunchingWithOptions method (refer the requesting push notification permission section above for more details on this)
extension AppDelegate: UNUserNotificationCenterDelegate {
// below method will be called when the user interacts with the push notification
func userNotificationCenter(
_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
// If this notification is Klaviyo's notification we'll handle it
// else pass it on to the next push notification service to which it may belong
let handled = KlaviyoSDK().handle(notificationResponse: response, withCompletionHandler: completionHandler)
if !handled {
completionHandler()
}
}
// below method is called when the app receives push notifications when the app is the foreground
func userNotificationCenter(
_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
if #available(iOS 14.0, *) {
completionHandler([.list, .banner])
} else {
completionHandler([.alert])
}
}
}
一旦您的第一个推送通知被发送和打开,您应该会在您的 Klaviyo 仪表板中开始看到 Opened Push 指标。
ℹ️ 您的应用程序需要使用最低 1.7.2 版本才能使以下步骤生效。
深度链接允许您响应用户打开推送通知而导航到应用程序中的特定页面。
您需要在应用程序中配置深度链接才能使其正常工作。 Klaviyo 的配置过程与处理深度链接通常所需的过程没有区别,因此您可以按照 Apple 文档进行深度链接,并结合此处概述的步骤。
您有两种实现深度链接的选项:URL schemes 和通用链接。
URL schemes 是从推送通知到应用程序进行深度链接的传统且更简单的方式。 但是,这些链接仅在您的移动应用程序安装在设备上时才有效,并且如果例如您想从电子邮件链接到您的应用程序,则 Web 浏览器将无法理解它们。
为了使 Apple 将深度链接路由到您的应用程序,您需要在应用程序的 Info.plist 文件中注册一个 URL scheme。 这可以使用 xcode 从项目设置的 Info 选项卡提供的编辑器完成,也可以直接编辑 Info.plist。
所需的字段如下:
为了直接编辑Info.plist,只需填写您应用程序的特定详细信息,然后将其粘贴到您的plist中。
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLName</key>
<string>{your_unique_identifier}</string>
<key>CFBundleURLSchemes</key>
<array>
<string>{your_URL_scheme}</string>
</array>
</dict>
</array>
自 iOS 9 以来,Apple 强制规定您的应用程序可以打开的 URL schemes 也需要列在 Info.plist 中。 这是对上述步骤 1 的补充。 即使您的应用程序没有打开任何其他应用程序,您仍然需要列出您应用程序的 URL scheme,以便深度链接正常工作。
这需要在 Info.plist 中直接完成
<key>LSApplicationQueriesSchemes</key>
<array>
<string>{your custom URL scheme}</string>
</array>
步骤 1 和步骤 2 使您的应用程序能够接收深度链接,但您还需要在您的应用程序中处理这些链接。 这是通过在您的应用程序委托中实现 application:openURL:options:
方法来完成的。
示例
func application(
_ app: UIApplication,
open url: URL,
options: [UIApplication.OpenURLOptionsKey : Any] = [:]
) -> Bool {
guard let components = NSURLComponents(url: url, resolvingAgainstBaseURL: true)
else {
print("Invalid deep linking URL")
return false
}
print("components: \(components.debugDescription)")
return true
}
如果您使用的是 SwiftUI,那么您可以实现 onOpenURL(perform:)
作为您打算处理深度链接的视图中的视图修饰符。 这可能不是您场景的根。
示例
@main
struct MyApplication: App {
var body: some Scene {
WindowGroup {
ContentView()
.onOpenURL { url in
// handle the URL that must be opened
}
}
}
}
最后,我们在 SDK 仓库中有一个示例应用程序 (Examples/KlaviyoSwiftExamples
),您可以参考该应用程序来获取如何在您的应用程序中实现深度链接的示例。
完成上述步骤后,您可以从 Klaviyo 网站内的 Klaviyo Push 编辑器发送推送通知。 在这里,您可以构建并通过 Klaviyo 发送推送通知,以确保 URL 出现在您在步骤 3 中实现的处理器中。
此外,您还可以本地触发深度链接,以确保您的代码使用终端中的以下命令正常工作。
xcrun simctl openurl booted {您的_URL_在此}
通用链接 是一种更现代的深度链接处理方式,也是 Apple 推荐的方式。 它们更安全,并提供更好的用户体验。 但是,与 URL schemes 不同,它们需要更多的设置,这些设置在 这些 Apple 文档中突出显示。
一旦您完成了 Apple 文档中的设置,您将需要修改推送打开跟踪,如下所述
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let handled = KlaviyoSDK().handle(notificationResponse: response, withCompletionHandler: completionHandler) { url in
print("deep link is ", url)
}
if !handled {
// not a klaviyo notification should be handled by other app code
}
}
}
请注意,深度链接处理程序将在主线程上被回调。 如果您除了通用链接之外还想处理 URL schemes,您可以按照 选项 1:URL Schemes 中所述的方式实现它们。
ℹ️ SDK 版本 2.2.0 及更高版本支持富媒体推送通知
富媒体推送 是将图像添加到推送通知消息的功能。 完成 安装 部分中的步骤后,您应该在您的项目中设置一个通知服务扩展,其中包含来自 KlaviyoSwiftExtension
的代码。 以下是如何测试富媒体推送通知的说明。
{
"aps": {
"alert": {
"title": "Free apple vision pro",
"body": "Free Apple vision pro when you buy a Klaviyo subscription."
},
"mutable-content": 1
},
"rich-media": "https://www.apple.com/v/apple-vision-pro/a/images/overview/hero/portrait_base__bwsgtdddcl7m_large.jpg",
"rich-media-type": "jpg"
}
AppDelegate
中的 didRegisterForRemoteNotificationsWithDeviceToken
方法输出到控制台。一旦您有了这三样东西,您就可以使用推送通知测试器并发送本地推送通知,以确保一切都已正确设置。
ℹ️ SDK 版本 4.1.0 及更高版本支持设置或递增徽章计数
当您发送推送通知时,Klaviyo 支持设置或递增徽章计数。 为了使此功能正常工作,您必须按照 安装 部分概述的方式设置通知服务扩展和应用程序组。
默认情况下,Klaviyo SDK 会在应用程序打开时自动清除徽章计数。 如果您想禁用此行为,请在您应用程序的 Info.plist
中为 klaviyo_badge_autoclearing
添加一个新条目,作为一个布尔值设置为 NO
。 您可以通过将此值设置为 YES
来重新启用自动清除徽章。
Klaviyo SDK 将自动处理与 Klaviyo 推送相关的徽章计数。 如果您需要手动更新徽章计数以考虑其他通知来源,请使用 KlaviyoSDK().setBadgeCount(:)
方法,该方法将更新徽章计数并使其与 Klaviyo SDK 保持同步。 此方法应代替(而不是补充)使用 UNUserNotificationCenter
和/或 UIApplication
方法设置徽章计数。
ℹ️ SDK 版本 2.2.0 及更高版本支持沙盒
Apple 有两个支持推送通知的环境 - 生产环境和沙盒环境。 生产环境支持在应用程序在 App Store 或 TestFlight 中发布时向真实用户发送推送通知。 相比之下,支持推送通知的沙盒应用程序是那些使用 iOS 开发证书而不是 iOS 发布证书签名的应用程序。 沙盒充当一个暂存环境,允许您在类似于但不同于生产环境的环境中测试您的应用程序,而无需担心向真实用户发送消息。
我们的 SDK 也支持将沙盒用于推送。 Klaviyo 的 SDK 将确定并存储您的推送令牌所属的环境,并将其传达给我们的后端,从而允许您的令牌将发送路由到正确的环境。 无需其他设置。 只要您已将您的应用程序部署到沙盒并使用我们的 SDK 将推送令牌传输到我们的后端,那么在这些沙盒应用程序上发送和接收推送的功能应该可以开箱即用。
从 1.7.0 版本开始,SDK 将缓存传入数据并以一定的时间间隔将其刷新回 Klaviyo API。 时间间隔基于应用程序当前使用的网络链接。 下表显示了每种连接类型使用的刷新时间间隔
网络 | 时间间隔 |
---|---|
WWAN/Wifi | 10 秒 |
蜂窝网络 | 30 秒 |
连接确定基于来自我们的可达性服务的通知。 当没有网络可用时,SDK 将缓存数据,直到网络再次可用。 SDK 发送的所有数据应该在 SDK 刷新后不久即可使用。
SDK 将在某些条件下重试失败的 API 请求。 例如,如果发生网络超时,请求将在下一个刷新时间间隔重试。 此外,如果 SDK 从 Klaviyo API 收到速率限制错误 429
,它将使用带抖动的指数退避来重试下一个请求。
请参阅贡献指南,了解如何为 Klaviyo Swift SDK 做出贡献。 我们欢迎您在我们的公共 GitHub 存储库的问题部分中提供反馈。
KlaviyoSwift 在 MIT 许可下可用。 有关更多信息,请参见 LICENSE 文件。