Klaviyo Swift SDK允许开发人员合并Klaviyo的分析,并将通知功能推送到其iOS应用程序中。 SDK通过Klaviyo客户端API来协助识别用户和跟踪事件。为了减少性能开销,API请求排队并分批发送。队列持续到本地存储,因此如果设备离线或应用程序终止,则不会丢失数据。
一旦整合,您的营销团队将能够更好地了解您的应用程序用户的需求,并通过APN及时发送消息。
在XCode项目中启用推送通知功能。本苹果开发人员指南中的“启用推送通知能力”部分提供了详细的说明。
[可选但推荐]如果您打算使用丰富的推送通知,请在Xcode项目中添加通知服务扩展。通知服务应用程序扩展程序作为iOS应用程序中的单独捆绑包。将此扩展名添加到您的应用中:
配x 您的通知服务扩展名的部署目标默认为最新的iOS版本。如果这超过了您的应用程序最低支持的iOS版本,则推送通知可能不会在较旧设备上显示附加的媒体。为了避免这种情况,请确保扩展名的最小部署目标与您的应用程序相匹配。配x
根据您使用的依赖关系管理器,请按照以下说明安装Klaviyo的依赖项。
Klaviyoswift可通过Swift Package Manager获得。请按照以下步骤安装。
https://github.com/klaviyo/klaviyo-swift-sdk
。这应该在屏幕上提出包装。KlaviyoSwift
分配给您的应用程序目标,并将KlaviyoSwiftExtension
分配给Notification Service Service扩展目标(如果创建了),然后单击“添加软件包” 。可以通过Cocoapods获得Klaviyoswift。
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帐户(也称为您的站点ID)的简短字母数字公共API密钥初始化。
// 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
}
}
在调用任何其他Klaviyo SDK方法之前,应初始化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 : " [email protected] " , 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 : " [email protected] " , firstName : " Blob " , lastName : " Jr. " )
KlaviyoSDK ( ) . set ( profile : profile )
// stop tracking Blob Jr.
KlaviyoSDK ( ) . resetProfile ( )
// start a profile for Robin Hood
let profile = Profile ( email : " [email protected] " , firstName : " Robin " , lastName : " Hood " )
KlaviyoSDK ( ) . set ( profile : profile )
每当设置推动令牌或创建事件时,Klaviyo将使用自动化ID跟踪身份不明的用户。这样,您可以在收集个人资料标识符(例如电子邮件或电话号码)之前收集推送令牌并跟踪事件。当提供标识符时,Klaviyo将将匿名用户与已确定的用户合并。
SDK提供了用于跟踪用户通过创建客户端事件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
Enum。可以在Event.EventName
中找到常见的klaviyo定义事件指标的列表。您还可以使用Event.EventName
的CustomEvent
Enum Case创建自定义事件properties
:特定于事件的属性字典。该论点是可选的。value
:与此事件相关联的数字值( Double
)。例如,购买的美元金额。 为了向用户发送推送通知,您必须收集其推送令牌并向Klaviyo注册。这是通过KlaviyoSDK().set(pushToken:)
方法完成的,该方法通过创建客户端推送令牌API注册了推动令牌和当前授权状态。
registerForRemoteNotifications()
请求apns的推送令牌。这通常是在application:didFinishLaunchingWithOptions:
您的应用程序委托的方法。application:didRegisterForRemoteNotificationsWithDeviceToken
以接收APN的推送令牌并向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 )
}
获得推送令牌后,下一步是请求您的用户许可,以发送推送通知。您可以在应用程序中的任何位置添加权限请求代码,在该请求中有意义地提示用户获取此权限。苹果提供了一些有关何时以及如何征求此许可的最佳实践指南。以下示例演示了如何在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 ] )
}
}
}
在跟踪打开的推送通知时,您还可以通过将以下代码添加到userNotificationCenter:didReceive:withCompletionHandler
方法:
func userNotificationCenter (
_ center : UNUserNotificationCenter ,
didReceive response : UNNotificationResponse ,
withCompletionHandler completionHandler : @escaping ( ) -> Void ) {
// decrement the badge count on the app icon
if #available ( iOS 16 . 0 , * ) {
UNUserNotificationCenter . current ( ) . setBadgeCount ( UIApplication . shared . applicationIconBadgeNumber - 1 )
} else {
UIApplication . shared . applicationIconBadgeNumber -= 1
}
// 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 ( )
}
}
此外,如果您只想在打开应用程序时将徽章计数重置为零(请注意,这可以是从用户单独打开应用程序独立于推送消息的用户),则可以在applicationDidBecomeActive
程序中添加以下代码应用委托:
func applicationDidBecomeActive ( _ application : UIApplication ) {
// reset the badge count on the app icon
if #available ( iOS 16 . 0 , * ) {
UNUserNotificationCenter . current ( ) . setBadgeCount ( 0 )
} else {
UIApplication . shared . applicationIconBadgeNumber = 0
}
}
发送并打开第一个推送通知后,您应该开始在Klaviyo仪表板中看到打开的推动指标。
您的应用需要最少使用1.7.2版,以便以下步骤工作。
深层链接使您可以响应用户打开推送通知,从而导航到应用程序中的特定页面。
您需要配置应用程序中的深层链接才能使它们工作。 Klaviyo的配置过程与一般处理深链接所需的配置过程没有什么不同,因此您可以按照Apple文档进行访问,以与此处概述的步骤结合使用。
您有两个可以实现深层链接的选项:URL方案和通用链接。
URL方案是从推送通知到应用程序的传统和简单链接的传统方式。但是,这些链接只有在设备上安装您的移动应用程序时才有效,并且网络浏览器不会理解,例如,如果您想将电子邮件从电子邮件链接到应用程序。
为了使Apple将深入链接路由到您的应用程序,您需要在应用程序的Info.plist文件中注册URL方案。可以使用XCode从项目设置的“信息”选项卡提供的编辑器或直接编辑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方案也需要在info.plist中列出。这是上面步骤1的补充。即使您的应用程序未打开任何其他应用程序,您仍然需要列出您的应用程序的URL计划,以便深入链接工作。
这需要在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推送编辑器中发送推送通知。在这里,您可以通过Klaviyo构建并发送推送通知,以确保在步骤3中实现的处理程序中显示URL。
此外,您还可以在本地触发深层链接,以确保您的代码使用终端中的以下命令正常工作。
xcrun simctl openurl booted {your_URL_here}
通用链接是一种更现代的处理深层链接的方式,并由苹果推荐。它们更安全,并提供更好的用户体验。但是,与URL方案不同,它们需要更多的设置,这些设置在这些Apple文档中突出显示。
从Apple Docs进行设置后,您将需要修改按下所述的推动开放跟踪:如下所述:
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方案,则如选项1:URL方案中所述实现它们。
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版本2.2.0及更高版本中有沙盒支持
苹果有两个环境,并具有推送通知支持 - 生产和沙箱。生产环境支持在应用程序商店或TestFlight发布应用程序时向真实用户发送推送通知。相比之下,支持推送通知的沙盒应用程序是iOS开发证书签名的,而不是iOS发行证书。沙盒充当阶段环境,使您可以在类似但与生产不同的环境中测试应用程序,而不必担心向真实用户发送消息。
我们的SDK也支持使用沙箱进行推动。 Klaviyo的SDK将确定并存储您的推动令牌所属的环境并将其传达给我们的后端,从而使您的令牌可以路由发送到正确的环境。无需其他设置。只要您将应用程序部署到Sandbox上,我们使用我们的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许可获得。有关更多信息,请参见许可证文件。