engageCore-ObjC 1.0.5

engageCore-ObjC 1.0.5

Diagnalbibin维护。



 
依赖于
Alamofire~> 4.5.0
AlamofireObjectMapper>= 0
SDVersion>= 0
 

  • 作者:
  • 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,请运行以下命令来安装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相关联。通常,在Traits类的`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 字典 参数字典。

示例 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:您需要在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 didFinishRegisterForRemoteNotificationsWithDeviceToken方法中收到回调。下一步是,您需要使用方法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 中,选择 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 {
}

通知 SDK 收到/打开的事件通知

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

您可以通过检查 Engage.onNotificationOpened 返回的空对象来验证接收到的通知是否来自 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的更多详细信息,请参阅苹果文档

辅助类

辅助类提供了一种简单的方法来集成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)