Klaviyo Swift SDK를 통해 개발자는 Klaviyo의 분석을 통합하고 알림 기능을 iOS 응용 프로그램에 통합 할 수 있습니다. SDK는 Klaviyo 클라이언트 API를 통해 사용자를 식별하고 이벤트를 추적하는 데 도움이됩니다. 성능 오버 헤드를 줄이기 위해 API 요청이 대기되어 배치로 전송됩니다. 큐는 로컬 스토리지로 유지되므로 장치가 오프라인 상태이거나 앱이 종료되면 데이터가 손실되지 않습니다.
일단 통합되면 마케팅 팀은 앱 사용자의 요구를 더 잘 이해하고 APN을 통해 적시 메시지를 보낼 수 있습니다.
Xcode 프로젝트에서 푸시 알림 기능을 활성화하십시오. 이 Apple 개발자 안내서의 "푸시 알림 기능 활성화"섹션은 자세한 지침을 제공합니다.
[선택 사항이지만 권장] Rich Push Atmalifications를 사용하려는 경우 Xcode 프로젝트에 알림 서비스 확장을 추가하십시오. Notification Service App Extension은 iOS 앱 내에서 별도의 번들로 선박을 선사합니다. 이 확장자를 앱에 추가하려면 :
켈 알림 서비스 확장의 배포 대상은 최신 iOS 버전으로 기본적으로 기본적으로 표시됩니다. 이것이 앱의 최소 지원 iOS 버전을 초과하면 푸시 알림이 이전 장치에 첨부 된 미디어를 표시하지 않을 수 있습니다. 이를 피하려면 확장자의 최소 배포 대상이 앱과 일치하는지 확인하십시오.켈
사용하는 종속성 관리자를 기반으로 아래 지침에 따라 Klaviyo의 종속성을 설치하십시오.
Klaviyoswift는 Swift 패키지 관리자를 통해 제공됩니다. 아래 단계를 따라 설치하십시오.
https://github.com/klaviyo/klaviyo-swift-sdk
의 URL을 입력하십시오. 화면에 패키지를 가져와야합니다.KlaviyoSwift
앱 대상에 할당하고 KlaviyoSwiftExtension
알림 서비스 확장 대상 (생성 된 경우)에 할당하고 패키지 추가를 클릭하십시오.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는 사이트 ID라고도 알려진 Klaviyo 계정의 짧은 영숫자 공개 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
}
}
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 : " [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는 사용자가 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
이름 열거로 추적하려는 이벤트의 이름. 일반적인 Klaviyo 정의 이벤트 메트릭 목록은 Event.EventName
에서 찾을 수 있습니다. CustomEvent
enum Event.EventName
을 사용하여 사용자 정의 이벤트를 만들 수도 있습니다.properties
: 이벤트와 관련된 속성 사전. 이 주장은 선택 사항입니다.value
:이 이벤트와 연결하는 숫자 값 ( Double
). 예를 들어, 구매 금액. 사용자에게 푸시 알림을 보내려면 푸시 토큰을 수집하여 Klaviyo에 등록해야합니다. 이것은 KlaviyoSDK().set(pushToken:)
메소드를 통해 수행되며, Create Client Client Push Token API를 통해 푸시 토큰 및 현재 권한 부여 상태를 등록합니다.
registerForRemoteNotifications()
호출하십시오. 이것은 일반적으로 application:didFinishLaunchingWithOptions:
앱 대의원의 메소드.application:didRegisterForRemoteNotificationsWithDeviceToken
사용하십시오.아래는 위의 두 단계를 모두 수행하는 코드입니다.
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
in apply in uspletionhandler 앱이 각각 백그라운드 및 전술에있을 때 푸시 알림을 처리하도록 처리합니다.
아래는 앱 대의원에서 푸시 알림을 처리하는 방법의 예입니다.
// 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
이 열렸을 때 배지 수를 0으로 재설정하려면 앱 대의원 :
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를 사용해야합니다.
Deep Links를 사용하면 사용자가 푸시 알림을 열면 앱 내 특정 페이지로 이동할 수 있습니다.
작업을 위해 앱에서 깊은 링크를 구성해야합니다. 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를 사용하는 경우 딥 링크를 처리하려는 뷰에서 view 수정 자로 onOpenURL(perform:)
구현할 수 있습니다. 이것은 당신의 장면의 근원 일 수도 있고 아닐 수도 있습니다.
예:
@ main
struct MyApplication : App {
var body : some Scene {
WindowGroup {
ContentView ( )
. onOpenURL { url in
// handle the URL that must be opened
}
}
}
}
마지막으로 SDK Repo에는 앱에서 깊은 링크를 구현하는 방법에 대한 예를 얻을 수있는 예제 앱 ( Examples/KlaviyoSwiftExamples
)이 있습니다.
위의 단계가 완료되면 Klaviyo 웹 사이트 내에서 Klaviyo 푸시 편집기에서 푸시 알림을 보낼 수 있습니다. 여기서는 Klaviyo를 통해 푸시 알림을 구축하여 보낼 수 있으며 3 단계에서 구현 한 핸들러에 URL이 나타나는지 확인할 수 있습니다.
또한 코드가 터미널의 아래 명령을 사용하여 코드가 작동하는지 확인하기 위해 로컬로 깊은 링크를 트리거 할 수도 있습니다.
xcrun simctl openurl booted {your_URL_here}
Universal Links는 더 현대적인 링크를 처리하는 방법이며 Apple이 권장합니다. 그들은 더 안전하고 더 나은 사용자 경험을 제공합니다. 그러나 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 체계 외에 URL 구성표를 처리하려면 옵션 1 : URL 구성표에 설명 된대로 구현하십시오.
풍부한 푸시 알림은 SDK 버전 2.2.0 이상에서 지원됩니다.
Rich Push는 푸시 알림 메시지를 위해 이미지를 추가하는 기능입니다. 설치 섹션의 단계가 완료되면 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
의 deviceToken 방법으로 didRegisterForRemoteNotificationsWithDeviceToken
에서 콘솔에 인쇄 할 수 있습니다.이 세 가지가 있으면 푸시 알림 테스터를 사용하여 로컬 푸시 알림을 보내 모든 것이 올바르게 설정되었는지 확인할 수 있습니다.
샌드 박스 지원은 SDK 버전 2.2.0 이상으로 제공됩니다.
Apple은 푸시 알림 지원이 포함 된 두 가지 환경의 생산 및 샌드 박스를 가지고 있습니다. 프로덕션 환경은 앱이 App Store 또는 TestFlight에 게시 될 때 실제 사용자에게 푸시 알림을 보내는 것을 지원합니다. 대조적으로, 푸시 알림을 지원하는 샌드 박스 응용 프로그램은 iOS 배포 인증서 대신 iOS 개발 인증서와 서명 된 응용 프로그램입니다. 샌드 박스는 스테이징 환경 역할을하여 실제 사용자에게 메시지를 보내는 것에 대해 걱정할 필요없이 생산과 유사한 환경에서 응용 프로그램을 테스트 할 수 있습니다.
우리의 SDK는 푸시 용 샌드 박스 사용을 지원합니다. Klaviyo의 SDK는 푸시 토큰이 속한 환경을 결정하고 저장하고이를 백엔드에 전달하여 토큰이 올바른 환경으로 전송되도록합니다. 추가 설정이 필요하지 않습니다. 푸시 토큰을 백엔드로 전송하기 위해 SDK를 사용하여 샌드 박스에 응용 프로그램을 배포 한 한 이러한 샌드 박스 애플리케이션을 보내고받을 수있는 기능은 상자 밖으로 작동해야합니다.
버전 1.7.0부터 SDK는 들어오는 데이터를 캐시하고 간격으로 Klaviyo API로 다시 플러시합니다. 이 간격은 현재 앱에서 사용중인 네트워크 링크를 기반으로합니다. 아래 표는 각 유형의 연결에 사용되는 플러시 간격을 보여줍니다.
회로망 | 간격 |
---|---|
Wwan/Wi -Fi | 10 초 |
셀룰러 | 30 초 |
연결 결정은 도달 가능성 서비스의 알림을 기반으로합니다. 사용 가능한 네트워크가 없으면 SDK는 네트워크를 다시 사용할 수있을 때까지 데이터를 캐시합니다. SDK가 보낸 모든 데이터는 SDK에 의해 플러시 된 직후에 사용할 수 있어야합니다.
SDK는 특정 조건에서 실패하는 API 요청을 재 시도합니다. 예를 들어, 네트워크 타임 아웃이 발생하면 다음 플러시 간격으로 요청이 재조정됩니다. 또한 SDK가 Klaviyo API로부터 속도 제한 오류 429
수신하는 경우 다음 요청을 다시 시도하기 위해 지터와 지수 백 오프를 사용합니다.
Klaviyo Swift SDK에 기여하는 방법을 배우려면 기고 가이드를 참조하십시오. 공개 Github 저장소의 문제 섹션에서 귀하의 의견을 환영합니다.
Klaviyoswift는 MIT 라이센스로 제공됩니다. 자세한 내용은 라이센스 파일을 참조하십시오.