engageCoreServiceExtension-ObjC 1.0.5

engageCoreServiceExtension-ObjC 1.0.5

Diagnalbibin 维护。



  • Diagnal

N|Solid

Engage iOS SDK

Engage 是驱动用户获取和转换的实时定向营销活动。它向用户推广内容并访问客户情绪。

Engage iOS SDK 通过几步即可轻松将 Engage 集成到您的 iOS 应用程序中。Engage iOS SDK 需要 iOS 8.0 或更高版本。Engage iOS SDK 现在支持 swift 2.3 和 swift 3。

Swift 2.3 最新库版本:2.0.0

Swift 3.0 最新库版本:3.0.0

资源

入门

第 1 步:安装框架

将 Engage iOS SDK 引入您的iOS项目有两种方式:CocoaPods 手动操作。您应该用这两种方式之一引入 Engage iOS SDK,但不要用多种方式。以多种方式引入 SDK 会导致项目加载 SDK 的多个副本,并导致编译错误。

CocoaPods

  1. Engage iOS SDK可通过CocoaPods获取。如果您还没有安装CocoaPods,请运行以下命令进行安装:

$ gem install cocoapods $ pod setup

根据您的系统设置,您可能需要使用sudo安装cocoapods,如下所示:

`$ sudo gem install cocoapods`
`$ pod setup`
  1. 在您的项目目录(即您的*.xcodeproj文件所在的目录)中,创建一个名为Podfile的纯文本文件(无需任何文件扩展名),并添加以下行。将YourTarget替换为您的实际目标名称。
source 'https://github.com/CocoaPods/Specs.git'

platform :ios, '8.0'
use_frameworks!

target :'YourTarget' do
pod 'engageCore'
end
  1. 然后运行以下命令:

$ pod install

  1. 使用Xcode打开*.xcworkspace并开始使用SDK。

步骤 2:初始化客户端

SDK的入口是Engage类。我们建议您在实现UIApplicationDelegate类中的application(_:didFinishLaunchingWithOptions:)方法中初始化客户端。

//Swift 2.3
Engage.initialize(application,didFinishLaunchingWithOptions: launchOptions, accountId: "ENGAGE_ACCOUNT_ID", projectId: "ENGAGE_PROJECT_ID")

//Swift 3.0
Engage.initialize(application: application,
didFinishLaunchingWithOptions:launchOptions,
accountId: "ENGAGE_ACCOUNT_ID",
projectId: "ENGAGE_PROJECT_ID")

ENGAGE_ACCOUNT_IDENGAGE_PROJECT_ID可从您的Enage仪表板获取

使用方法

识别用户

通过identify方法,可以将您的用户及其行为与可识别的userIdTraits相关联。Trait init方法中的所有参数都是可选的。

let traits = Traits(id: userId,
                    name: fullName,
                    email: email,
                    gender: genderValue,
                    age: age,
                    status: registrationStatus,
                    city: city,
                    country: country,
                    network: network,
                    customTraits: customTraits)
//Swift 2.3
Engage.identify(traits)

//Swift 3.0
Engage.identify(traits: traits)

如果Traits没有初始化userId,则用户将被视为匿名。

identify调用示例

let traits = Traits(id: "4981498",
                    name: "Sudeep",
                    gender: GENDER.MALE,
                    age: 28,
                    status: "subscribed",
                    country: "India")

//Swift 2.3
Engage.identify(traits)

//Swift 3.0
Engage.identify(traits: traits)

跟踪

《track》方法让您记录用户执行的任何操作。您可以在指南中查看跟踪示例或找到有关跟踪方法有效负载的详细信息。

//Swift 2.3
Engage.track("eventName", params: params)

//Swift 3.0
Engage.track(eventName: "eventName", params: params)

《track》方法有以下参数:

参数 类型 描述
eventName 字符串 您要跟踪的事件名称。
params <[NSObject : AnyObject]> 参数的字典。

示例 track 调用

//Swift 2.3
var params = [NSObject : AnyObject]()
params["content_title"] = "How to Create a Tracking Plan"
params["content_id"] = "1234"
Engage.track("play_content", params: params)

//Swift 3.0
var params = [AnyHashable : Any]()
params["content_title"] = "How to Create a Tracking Plan"
params["content_id"] = "1234"
Engage.track(eventName: "play_content", params: params)

使用内置事件

Engage iOS SDK 预建事件让您能够跟踪应用程序中最常用的特定操作和事件。例如,内容视图事件可以记录如下:

//Swift 2.3
let eventCreator = ContentEventCreator(contentId: "series_2332")
 eventCreator.putType("series")
			 .putTitle("Game of thrones")
			 .putSource("Details page")
Engage.track(event.onContentView())

//Swift 3.0
let eventCreator = ContentEventCreator.init(contentId: contentID!).putType(type: "Movie").putTitle(title:  "Test Title")
Engage.track(event: event.onContentView())
            

Engage iOS SDK 支持以下事件创建器:

事件创建器 描述
ApplicationEventCreator 应用程序事件事件的事件创建器
AdvertisementEventCreator 广告播放事件的事件创建器
ContentEventCreator 媒体内容事件的事件创建器
DownloadEventCreator 内容下载事件的事件创建器
PlayerEventCreator 媒体播放事件的事件创建器
PurchaseEventCreator 购买事件的事件创建器
SearchEventCreator 搜索事件的事件创建器
UserEventCreator 用户事件的事件创建器

注意:为了跟踪 AppLaunch 事件,应从 UIApplicationDelegate 实现类中的 application(_:didFinishLaunchingWithOptions:) 调用 ApplicationEventCreatoronAppLaunch() 事件。

//Swift 2.3
Engage.track(ApplicationEventCreator().onAppLaunch())

//Swift 3.0
Engage.track(event: ApplicationEventCreator().onAppLaunch())

活动

SDK 在活动页面上定义的事件上触发活动。您可以为 CampaignEventDelegate 注册以了解何时触发活动,并根据用户与活动的交互获取操作字符串。

//Swift 2.3
Engage.registerForCampaignEvents(campaignEventDelegateImpl)

//Swift 3.0
Engage.registerForCampaignEvents(campaignEventDelegate: self)

CampaignEventDelegate 应由 CampaignEventDelegateImpl 对象实现。

func onCampaignTriggered(campaign : EngageCampaign) -> Bool {
///Return false if you don't want to show the campaign dialog
return true
}

func onCampaignAction(campaign : EngageCampaign) {
//use campaign object properties to perform appropriate actions in your roject
}

推送通知

Engage 支持推送通知活动,这是一种非常强大的运行定向活动的方式。请按照以下步骤配置推送通知:

APNS 设置

要在 Engage 中使推送通知活动运行,您需要为推送服务配置您的应用程序。有关此过程的详细信息,请参阅APNS 设置文档

注册通知

步骤 1:转到您的项目目标并点击“功能”,确保已启用“推送通知”,并在“后台模式”下选中“远程通知”。

步骤 2:您需要在 UIApplicationDelegatedidFinishLaunchingWithOptions 方法中注册远程通知。

//swift2.3
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
	let settings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
	application.registerUserNotificationSettings(settings)
	application.registerForRemoteNotifications()
}

//Swift 3.0
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
            (granted, error) in
            if granted {
                application.registerForRemoteNotifications()
            }
        }
}

**步骤 3**:如果注册推送通知成功,您将在 UIApplicationDelegatedidRegisterForRemoteNotificationsWithDeviceToken 方法中收到回调。下一步,您需要使用方法 Engage.registerForRemoteNotificationsWithDeviceToken(deviceToken) 从 Engage 注册远程通知。

//Swift 2.3
//Register remote notifications from engage. 
func application(application: UIApplication, 					    didRegisterForRemoteNotificationsWithDeviceToken 
deviceToken: NSData) {
	Engage.registerForRemoteNotificationsWithDeviceToken(deviceToken)
}

//Swift 3.0
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {      Engage.registerForRemoteNotificationsWithDeviceToken(deviceToken: deviceToken)
}

告知 Engage SDK 推通知接收/打开事件

Engage 使用静默推送通知进行推送通知活动。为了使 Engage 推送通知活动正常工作,您需要告知 Engage SDK 您端的推送通知接收/打开事件。

您可以使用

//Swift 2.3
Engage.onNotificationRecieved(userInfo)
//Swift 3.0  
Engage.onNotificationRecieved(userInfo: userInfo)

//Swift 2.3
Engage.onNotificationOpened(userInfo)

//Swift 3.0
Engage.onNotificationRecieved(userInfo: userInfo)

告知 Engage SDK 推通知接收/打开事件。这两个方法都将返回一个非空的对象 NotificationData,如果接收到的是 Engage 通知。如果它返回一个非空的 NotificationData 对象,您可以在您的应用程序中轻松跳过处理这些通知。

步骤 1:在 UIApplicationDelegate 中实现 application(_:didReceiveRemoteNotification:fetchCompletionHandler:=) 方法。

首先,您需要确定是否调用 didReceiveRemoteNotification 是因为用户点击了推送通知,还是因为用户接收到了推送通知。您可以通过应用程序状态来识别这一点。

switch application.applicationState {
    case .active:
        //app is currently active, iOS won't be showing any notifications in this case. Applications needs to perform operations based on the user notifications.
        break
    case .inactive:
        //app is transitioning from background to foreground (user taps notification), do what you need when user taps here
        break
    case .background:
        //app is in background, and notification is just received when app is in background.Perform any background fetches if needed.
         break
}
//Swift 2.3
// Example
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
if(application.applicationState == .Inactive ) {
//User has interacted with a received notification. Inform Engage SDK a notification is opened
	if let notificationData = Engage.onNotificationOpened(userInfo) {
	 // Application can use the NotificationData object to perform any custom navigations , deep links etc.
	}
} 
else if (application.applicationState == .Background) {
//Inform Engage SDK that an event has been recieved.
  let notificationData = Engage.onNotificationRecieved(userInfo)
	}
else {
/*
Application is in Active State/ Foreground.
Inform Engage SDK that an event has been recieved.
Also ,since iOS won't be displaying a notification since application is already in foreground , application Developer can use the NotificationData object to show some custom inapp notifications or custom UI. if you are planning to show some custom UI / Inapp notifications , the you need to inform engage SDK if the user is interacted with that UI.

For iOS 10 and above you could use UNUserNotificationCenterDelegate to control whether you need to show the notification when application is in foreground.
*/
	let notificationData = Engage.onNotificationRecieved(userInfo)
	}
completionHandler(.NewData)
}

//Swift 3.0
func application(_ application: UIApplication,didReceiveRemoteNotification userInfo: [AnyHashable : Any],fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        if(application.applicationState == .inactive ) {
            //User has interacted with a received notification. Inform Engage SDK a notification is opened
            if let notificationData = Engage.onNotificationOpened(userInfo: userInfo) {
                // Application can use the NotificationData object to perform any custom navigations , deep links etc.
            }
        }
        else if (application.applicationState == .background) {
            //Inform Engage SDK that an event has been recieved.
            let notificationData = Engage.onNotificationRecieved(userInfo: userInfo)
        }
        else {
            /*
             Application is in Active State/ Foreground.
             Inform Engage SDK that an event has been recieved.
             Also ,since iOS won't be displaying a notification since application is already in foreground , application Developer can use the NotificationData object to show some custom inapp notifications or custom UI. if you are planning to show some custom UI / Inapp notifications , the you need to inform engage SDK if the user is interacted with that UI.
             
             For iOS 10 and above you could use UNUserNotificationCenterDelegate to control whether you need to show the notification when application is in foreground.
             */
            let notificationData = Engage.onNotificationRecieved(userInfo: userInfo)
        }
        completionHandler(.newData)
    }

深度推送通知活动(iOS 10及以上)

集成(添加通知服务扩展)

步骤 1:前往AppDelegate.swift文件,在appDelegate中导入UserNotification框架,并在didFinishLaunchingWithOptions方法中添加以下代码

UNUserNotificationCenter.currentNotificationCenter().delegate = self

步骤 2:您可以通过通知服务扩展启用深度推送通知。在您的项目中创建一个通知服务扩展。为此,在Xcode中,选择File -> New -> Target,然后选择通知服务扩展模板。

步骤 3:一旦您已添加通知服务扩展目标,您现在可以从pod中将 engageCoreServiceExtension 安装到您的通知扩展目标中。

您的最终pod文件将如下所示

source 'https://github.com/CocoaPods/Specs.git'

platform :ios, '8.0'
use_frameworks!

target :'YourTarget' do
pod 'engageCore'
end

target "Your Notification Extension" do
    inherit! :search_paths 
    pod 'engageCoreServiceExtension'
end

然后运行以下命令:

$ pod install

使用Xcode打开*.xcworkspace并开始使用SDK。

步骤 4:一旦您添加了新目标,您将有一个名为NotificationService.swift的新文件。

打开此类,使用EngageNotificationServiceExtension类扩展。此类的代码如下所示

import UserNotifications
import engageCoreServiceExtension
class NotificationService: EngageNotificationServiceExtension {
}

通知Engage SDK通知已接收/打开事件

步骤 1:您需要通知Engage SDK用户已打开深度推送通知。您可以通过实现 UNUserNotificationCenterDelegate didReceiveNotificationResponse 方法来完成此操作。

您可以通过检查 Engage.onNotificationOpened 返回的nil对象来验证接收到的通知是否来自Engage。

//Swift 2.3
if let notificationData = Engage.onNotificationOpened(response.notification.request.content.userInfo) {
//Notification from Engage
}

//Swift 3.0
if let notificationData = Engage.onNotificationOpened(userInfo: response.notification.request.content.userInfo) {
//Notification from Engage
}

此外,应用可以使用 response.actionIdentifier 检查用户是否通过点击通知或任何交互式按钮进行交互。

UNUserNotificationCenterDelegate 的实现如下:

extension AppDelegate : UNUserNotificationCenterDelegate  {
func userNotificationCenter(center: UNUserNotificationCenter, didReceiveNotificationResponse response: UNNotificationResponse, withCompletionHandler completionHandler: () -> Void) {
/* Called to let your app know which action was selected by the user for a given notification.Invoked when user taps on either notification or any custom interactive buttons in notifications.*/
 if let notificationData = Engage.onNotificationOpened(response.notification.request.content.userInfo) {
 if response.actionIdentifier == UNNotificationDefaultActionIdentifier {
  //User has interacted with the notification.
  }
  else {
  /*User has interacted with the notification interactive buttons.*/
  }
 }
}
    
func userNotificationCenter(center: UNUserNotificationCenter, willPresentNotification notification: UNNotification, withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void) {
/*Called when a notification is delivered to a foreground app.
Call completion handler if you want to display the notification even if the user is in foreground.*/ 
 completionHandler([.Alert])
}  
} 

//Swift 3.0

extension AppDelegate : UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void){
/* Called to let your app know which action was selected by the user for a given notification.Invoked when user taps on either notification or any custom interactive buttons in notifications.*/
 if let notificationData = Engage.onNotificationOpened(userInfo: response.notification.request.content.userInfo) {
 if response.actionIdentifier == UNNotificationDefaultActionIdentifier {
  //User has interacted with the notification.
  }
  else {
  /*User has interacted with the notification interactive buttons.*/
  }
 }
}
    
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
/*Called when a notification is delivered to a foreground app.
Call completion handler if you want to display the notification even if the user is in foreground.*/ 
    completionHandler(.alert)
}  
}

关闭用户

如果用户从您的应用程序登出,您需要通知Engage SDK停止跟踪当前用户的事件。

为了停止跟踪当前用户,您需要调用 Engage.shutDown()

在您调用 shutdown 之后,EngageSDK 将至您再次调用 identify 前停止所有事件跟踪。当新用户登录或您想跟踪匿名用户时,您需要再次调用 Engage.identify(traits)

支持 UNNotificationContentExtension

如果您想自定义丰富推送通知的 UI,您可以通过在应用程序中集成 UNNotificationContentExtension 来实现。

要在 Engage 推送通知触发时调用 UNNotificationContentExtension,您需要在 UNNotificationContentExtension 的 info.plist 中添加 UNNotificationExtensionCategory。

EngageSDK 在所有丰富推送通知中使用 UNNotificationExtensionCategoryengage.notifications

有关 UNNotificationContentExtension 的更多详细信息,请参阅 apple 文档

辅助类

辅助类提供了一个简单的方法来将 Engage iOS SDK Engage.track("eventName", params: params)集成到您已经使用的实时分析框架中。

我们目前支持 FirebaseAnalytics。

要使用辅助类,请将它们添加到您的项目中。请在此处找到 Firebase analytics 的辅助类 这里

如果您已经集成了 FirebaseAnalytics,只需将所有以 FIRAnalytics 开头的调用替换为 EngageFIRAnalytics

示例

替换

//Swift 2.3
FIRAnalytics.logEventWithName(name, parameters: parameters)

//Swift 3.0
Analytics.logEvent(name, parameters: parameters)

//Swift 2.3
EngageFIRAnalytics.logEventWithName(name, parameters: parameters)

//Swift 3.0
EngageFIRAnalytics.logEventWithName(name: name, parameters: parameters)