engageCoreServiceExtension 4.0.0

engageCoreServiceExtension 4.0.0

测试已测试
Lang语言 Obj-CObjective C
许可证 NOASSERTION
发布最后发布2017年10月

DiagnalbibinManikandan 维护。



  • 作者
  • Diagnal

N|Solid

Engage iOS SDK

Engage 是实时定向营销活动,可推动用户获取和转化。它向用户推广内容并获取客户情感。

Engage iOS SDK 允许通过几个步骤轻松将 Engage 集成到您的 iOS 应用程序中。Engage iOS SDK 需要 iOS 8.0 或更高版本。Engage iOS SDK 现在支持 swift 5.1 和 swift 5.2。

Swift 2.3 最新库版本:2.0.0

Swift 3.0 最新库版本:3.0.0

Swift 5.0 最新库版本:3.4.3

支持 Xcode 11 最新库版本:3.4.7

支持 Xcode 11.2 最新库版本:3.4.8

支持 Xcode 11.4 最新库版本:3.4.9

支持 Xcode 12 (Swift 5.3) 最新库版本:3.5.1

支持 Xcode 12.2 (Swift 5.3) 最新库版本:3.5.8

资源

入门

步骤 1:安装框架

将 Engage iOS SDK for iOS 导入项目的两种方式:CocoaPods 手动导入您应该选择这两种方式之一来导入 Engage iOS SDK,而不是多个。以多种方式导入 SDK 会在项目中加载 SDK 的副本,并导致编译错误。

CocoaPods

  1. Engage iOS SDK for iOS 通过 CocoaPods 提供使用。如果您尚未安装 CocoaPods,请运行以下命令进行安装:

$ gem install cocoapods $ pod setup

根据您的系统设置,您可能需要使用 sudo 以如下方式安装 cocoapods

`$ sudo gem install cocoapods`
`$ pod setup`
  1. 在您的项目目录(您的 *.xcodeproj 文件所在的目录),创建一个名为 Podfile 的纯文本文件(不带任何文件扩展名)并添加以下行。将 YourTarget 替换为您实际的 target 名称。
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 实现类的 方法中初始化客户端。

//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 仪表板 获取 ENGAGE_ACCOUNT_IDENGAGE_PROJECT_ID

用法

识别用户

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 String 您要跟踪的事件的名称。
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 支持以下事件创建者

事件创建者 描述
应用事件创建者 应用事件事件的创建者
广告事件创建者 广告播放事件的创建者
内容事件创建者 媒体内容事件的创建者
下载事件创建者 内容下载事件的创建者
播放器事件创建者 媒体播放事件的创建者
购买事件创建者 购买事件的创建者
搜索事件创建者 搜索事件的创建者
用户事件创建者 用户事件的创建者

注意:为了跟踪 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步:您需要从UIApplicationDelegate中的didFinishLaunchingWithOptions方法注册远程通知。

//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步**:如果注册推送通知成功,您将在UIApplicationDelegate的didRegisterForRemoteNotificationsWithDeviceToken方法中收到回调。下一步是,您需要使用方法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关于通知的接收/打开。这两种方法都会返回一个非nil的NotificationData对象,如果接收到的通知是Engage通知。如果您从返回的非nil 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.framework,并在didFinishLaunchingWithOptions中添加此代码。

UNUserNotificationCenter.currentNotificationCenter().delegate = self

步骤 2:您可以通过通知服务扩展启用富推送通知。在Xcode中,选择文件 > 新建 > 目标,并选择通知服务扩展模板。

步骤 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用户已打开富推送通知。您可以通过实现UNUserNotificationCenterDelegatedidReceiveNotificationResponse方法来完成。

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

//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)
}  
}

ShutDown User

如果用户从您的应用中注销,需要通知Engage SDK停止跟踪当前用户的事件。

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

调用shutdown后,EngageSDK将禁用所有事件跟踪,直到您再次调用identify。当新用户登录或您想要跟踪匿名用户时,请再次调用Engage.identify(traits)

支持UNNotificationContentExtension

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

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

EngageSDK用于所有富推送通知的UNNotificationExtensionCategoryengage.notifications

有关UNNotificationContentExtension的更多详细信息,请参考苹果文档

辅助类

辅助类为已使用事件分析框架的用户提供了轻松集成Engage iOS SDK(Engage.track("eventName", params: params))的方式

我们目前支持FirebaseAnalytics。

要使用辅助类,请将其添加到项目中。请在此找到FirebaseAnalytics的辅助类此处

如果您已经集成了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)