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許可獲得。有關更多信息,請參見許可證文件。