Intelligence SDK
该 SDK 的目标是以开发者友好的方式封装 Intelligence 平台的 API。
入门
I. 添加 IntelligenceSDK
在本节中,我们详细介绍了如何将 IntelligenceSDK 整合到基于 Objective-C 和 Swift 的项目中。
我们可以通过 Cocoapods、Carthage 或手动导入到您的应用中导入 SDK
A) 通过 Cocoapods
Intelligence 可通过 Cocoapods 使用。如果您是 Cocoapods 的初学者,可以使用以下命令进行安装
$ sudo gem install cocoapods
更多信息请参考入门指南。
要将 IntelligenceSDK 集成到您的 Xcode 项目中,请导航到包含您项目的目录,使用 pod init 创建一个新的 Podfile 或打开一个现有的 Podfile,然后将其添加到主循环中的 pod 'IntelligenceSDK'。如果您正在使用 Swift SDK,请确保添加 use_frameworks! 行。
$ pod init
打开为您的应用程序创建的 Podfile,并按以下操作添加到目标中
target 'YourTargetName' do
use_frameworks!
pod 'IntelligenceSDK'
end
然后,运行以下命令安装依赖项
pod install
这将为您创建一个 .xcworkspace 文件。使用此文件在您应用程序的所有未来开发上。
请记住,在安装后关闭所有当前的 XCode 会话,并使用 .xcworkspace 文件结束。如果打开您的 .xcworkspace 文件,您应该在 Pods 文件夹下看到 IntelligenceSDK 文件夹。
祝贺您,您已使用 CocoaPods 将 Intelligence iOS SDK 添加到您的项目!接下来,为了集成 Intelligence API。
B) 通过 Carthage
Intelligence 通过 Carthage 提供。您可以使用 Carthage 将 Intelligence 集成到您的项目中。如果您对 Carthage 不熟悉,请先查看他们的 文档。
您可以通过 Homebrew 安装 Carthage(Xcode 7+)
brew update
brew install carthage
要通过 Carthage 安装 IntelligenceSDK,您需要创建一个 Cartfile。在您的项目根目录下,运行以下命令
touch cartfile
使用您选择的编辑器打开文件,并添加以下内容
binary "https://raw.githubusercontent.com/tigerspike/Intelligence-iOS-Framework/master/IntelligenceSDK.json" ~> 2.0
使用特定版本的库(例如:1.0)
binary "https://raw.githubusercontent.com/tigerspike/Intelligence-iOS-Framework/master/IntelligenceSDK.json" == 1.0
有关 SDK 版本的更多信息,请参阅 此处。
现在运行以下命令以签出并构建我们的存储库和依赖项。
carthage update
现在您应该在项目目录中有一个 Carthage/Build 文件夹。打开您的 .xcodeproj,转到“通用”设置选项卡。在“链接框架和库”部分,将 Carthage/Build/iOS 中的每个框架(拖拽到其中)
现在,打开您的应用程序目标“构建阶段”设置选项卡,单击 + 图标,选择“新运行脚本阶段”。将以下内容添加到脚本区域
/usr/local/bin/carthage copy-frameworks
并将所需框架的路径添加到“输入文件”中
$(SRCROOT)/Carthage/Build/iOS/IntelligenceSDK.framework
对于 Objective-C 项目,将项目设置选项卡中“构建选项”下的“嵌入式内容包含 Swift 代码”标志设置为“是”。
祝贺您,您已使用 Carthage 将 Intelligence iOS SDK 添加到您的项目中!接下来,为了集成 Intelligence API。
C) 手动集成
-
从Github下载智能框架。
II. 导入SDK
接下来,导入IntelligenceSDK框架。
Swift
#!swift
import IntelligenceSDK
Objective-C
#!objc
@import IntelligenceSDK;
III. 创建与配置您的账户
在使用SDK之前,您需要一个智能账户。如果您没有智能账户,请联系[email protected]。对于Tigerspiker账户请求,请在此处。
III.1 配置JSON文件
IntelligenceSDK要求每个项目有一个配置JSON文件。所有这些变量都来自智能平台,并将包括在捆绑到iOS App的JSON文件中。
- "client_secret" (String):应用客户端密钥(仅当项目创建时提供。)。
- "client_id" (String):应用客户端ID(仅当项目创建时提供。)。
- "application_id" (Integer):您的智能应用程序ID。
- "project_id" (Integer):您的智能项目ID。
例如,创建的配置文件(intelligence.json)应如下所示:
{
"client_id": "CLIENT_ID",
"client_secret": "CLIENT_SECRET",
"application_id": 10,
"project_id": 20
}
III.2 初始化
Intelligence SDK需要委托和配置变量才能初始化自己。在SDK无法继续某种特定状态时,例如请求用户必须再次登录时,将调用委托。
1. 提供SDK配置的几种不同方式
A) 使用配置文件初始化智能服务
Swift
#!swift
do {
let intelligence = try Intelligence(withDelegate: self, file: "IntelligenceConfiguration")
}
catch {
// Treat the error with care!
}
Objective-C
#!objc
// Attempt to instantiate Intelligence using a JSON file.
NSError *err;
Intelligence *intelligence = [[Intelligence alloc] initWithDelegate: self file:@"IntelligenceConfiguration" inBundle:[NSBundle mainBundle] error:&err];
if (nil != err) {
// Handle error, developer needs to resolve any errors thrown here, these should not be visible to the user
// and generally indicate that something has gone wrong and needs to be resolved.
NSLog(@"Error initialising Intelligence: %zd", err.code);
}
NSParameterAssert(err == nil && intelligence != nil);
B) 初始化一个配置对象,读取文件并将其传递给智能服务
Swift
#!swift
do {
let configuration = try Intelligence.Configuration(fromFile: "IntelligenceConfiguration")
intelligence = try Intelligence(withDelegate: self, configuration: configuration)
}
catch {
// Treat the error with care!
}
Objective-C
#!objc
// Attempt to instantiate Intelligence using a JSON file.
NSError *err;
INTConfiguration *configuration = [[INTConfiguration alloc] initFromFile:@"IntelligenceConfiguration" inBundle:[NSBundle mainBundle] error:&err];
Intelligence *intelligence = [[Intelligence alloc] initWithDelegate: self configuration:configuration error:&err];
if (nil != err) {
// Handle error, developer needs to resolve any errors thrown here, these should not be visible to the user
// and generally indicate that something has gone wrong and needs to be resolved.
NSLog(@"Error initialising Intelligence: %zd", err.code);
}
NSParameterAssert(err == nil && intelligence != nil);
C) 在配置中程序化设置所需参数,并用它初始化智能服务。
Swift
#!swift
let configuration = Intelligence.Configuration()
configuration.clientID = "YOUR_CLIENT_ID"
configuration.clientSecret = "YOUR_CLIENT_SECRET"
configuration.projectID = 123456789
configuration.applicationID = 987654321
Objective-C
#!objc
INTConfiguration *configuration = [[INTConfiguration alloc] init];
configuration.clientID = @"YOUR_CLIENT_ID";
configuration.clientSecret = @"YOUR_CLIENT_SECRET";
configuration.projectID = 123456789;
configuration.applicationID = 987654321;
2. 实例化智能服务时的类应该符合IntelligenceDelegate。
Swift
extension YourClass : IntelligenceDelegate {
/// Credentials provided are incorrect. Will not distinguish between incorrect client or user credentials.
func credentialsIncorrect(for intelligence:
Intelligence) {
}
/// Account has been disabled and no longer active. Credentials are no longer valid.
func accountDisabled(for intelligence: Intelligence) {
}
/// Account has failed to authentication multiple times and is now locked. Requires an administrator to unlock the account.
func accountLocked(for intelligence: Intelligence) {
}
/// Token is invalid or expired, this may occur if your Application is configured incorrectly.
func tokenInvalidOrExpired(for intelligence: Intelligence) {
}
/// Unable to create SDK user, this may occur if a user with the randomized credentials already exists (highly unlikely) or your Application is configured incorrectly and has the wrong permissions.
func userCreationFailed(for intelligence: Intelligence) {
}
/// User is required to login again, developer must implement this method you may present a 'Login Screen' or silently call identity.login with stored credentials.
func userLoginRequired(for intelligence: Intelligence) {
// Present login screen or call identity.login with credentials stored in Keychain.
}
/// Unable to assign provided sdk_user_role to your newly created user. This may occur if the Application is configured incorrectly in the backend and doesn't have the correct permissions or the role doesn't exist.
func userRoleAssignmentFailed(for intelligence: Intelligence) {
}
}
Objective-C
/// Credentials provided are incorrect. Will not distinguish between incorrect client or user credentials.
- (void)credentialsIncorrectForIntelligence:(Intelligence * __nonnull)intelligence {
}
/// Account has been disabled and no longer active. Credentials are no longer valid.
- (void)accountDisabledForIntelligence:(Intelligence * __nonnull)intelligence {
}
/// Account has failed to authentication multiple times and is now locked. Requires an administrator to unlock the account.
- (void)accountLockedForIntelligence:(Intelligence * __nonnull)intelligence {
}
/// Token is invalid or expired, this may occur if your Application is configured incorrectly.
- (void)tokenInvalidOrExpiredForIntelligence:(Intelligence * __nonnull)intelligence {
}
/// Unable to create SDK user, this may occur if a user with the randomized credentials already exists (highly unlikely) or your Application is configured incorrectly and has the wrong permissions.
- (void)userCreationFailedForIntelligence:(Intelligence * __nonnull)intelligence {
}
/// User is required to login again, developer must implement this method you may present a 'Login Screen' or silently call identity.login with stored credentials.
- (void)userLoginRequiredForIntelligence:(Intelligence * __nonnull)intelligence {
}
/// Unable to assign provided sdk_user_role to your newly created user. This may occur if the Application is configured incorrectly in the backend and doesn't have the correct permissions or the role doesn't exist.
- (void)userRoleAssignmentFailedForIntelligence:(Intelligence * __nonnull)intelligence {
}
IV. 启动
重要的是,'启动'方法负责引导SDK,没有它,可能会发生未定义的行为,因此调用它是在使用SDK之前的开发者的责任。建议在初始化Intelligence对象后立即这样做,但可以在更方便的时候推迟。如果返回值为false,则可能配置不正确。你应从IntelligenceDelegate的方法之一接收到错误。
Swift
#!swift
// Startup all modules.
intelligence.startup { (success) -> () in
// Startup succeeded if success is true.
}
Objective-C
#!objc
// Startup the SDK...
[intelligence startup:^(BOOL success) {
// Startup succeeded if success is true.
}];
关闭
当您的应用程序终止时,您应调用关闭方法,以便SDK执行任何清理并存储任何与下次会话相关的信息。
Swift
#!swift
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
intelligence.shutdown()
}
Objective-C
#!objc
- (void)applicationWillTerminate:(UIApplication *)application {
// Shutdown Intelligence in the applicationWillTerminate method so Intelligence has time
// to teardown properly.
[intelligence shutdown];
}
V. 跟踪事件
要跟踪自定义事件
Swift: 注意:Swift中有一些可选字段,如果缺失,默认为零/nil。
#!swift
// Create custom Event
let myTestEvent = Event(withType: “Intelligence.Test.Event.Type”)
// Send event to Analytics module
intelligence.analytics.track(event: myTestEvent);
Objective-C
#!objc
// Create custom Event
INTEvent *myTestEvent = [[INTEvent alloc] initWithType:@"Intelligence.Test.Event.Type" value:1.0 targetId:5 metadata:nil];
// Send event to Analytics module
[intelligence.analytics track:myTestEvent];
如何跟踪屏幕视图事件
Swift
#!swift
// Duration is in seconds and can include fractional seconds
intelligence.analytics.trackScreenViewed("Main Screen", viewingDuration: 5)
Objective-C
#!objc
// Duration is in seconds and can include fractional seconds
[intelligence.analytics trackScreenViewedWithScreenName:@"Main Screen", viewingDuration: 5];
暂停/恢复跟踪
开发者负责在应用程序进入后台和前台时调用暂停和恢复方法。如果不调用这些方法,可能会产生意外的结果,并扭曲人工智能收集的统计数据。
Swift
#!swift
func applicationDidEnterBackground(application: UIApplication) {
intelligence.analytics.pause()
}
func applicationWillEnterForeground(application: UIApplication) {
intelligence.analytics.resume()
}
Objective-C
#!objc
- (void)applicationDidEnterBackground:(UIApplication *)application {
[[intelligence analytics] pause];
}
- (void)applicationWillEnterForeground:(UIApplication *)application {
[[intelligence analytics] resume];
}
注册设备令牌
作为开发者,你负责管理推送通知令牌,如果你的应用程序支持登录,应在登录成功后注册设备令牌。但是,如果你的应用程序没有登录/注销功能,应在启动成功后进行注册。你还应该管理是否以前注册了该设备令牌,因为你不想多次发送。
如何从Apple请求推送通知令牌的示例
#!swift
let application = UIApplication.sharedApplication()
application.registerForRemoteNotifications()
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: .Alert, categories: nil))
以下是如何响应委托方法 'didRegisterForRemoteNotificationsWithDeviceToken' 的示例
Swift
#!swift
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
IntelligenceManager.intelligence.identity.registerDeviceToken(deviceToken) { (tokenId, error) -> Void in
if error != nil {
// Failed, handle error.
} else {
// Successful! Store tokenId in Keychain you will need the Id in order to unregister.
}
}
}
Objective-C
#!objc
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
[[[INTIntelligenceManager intelligence] identity] registerDeviceToken:deviceToken callback:^(NSInteger tokenId, NSError * _Nullable error) {
if (error != nil) {
// Failed, handle error.
} else {
// Successful! Store tokenId in Keychain you will need the Id in order to unregister.
}
}];
}
‘registerDeviceToken’ 方法可以返回以下附加错误
- IdentityError.DeviceTokenInvalidError:提供的设备令牌无效。
注销设备令牌
开发者负责注销设备令牌,它们一次只能分配给一个用户,所以如果你忘记从上一个用户注销,你将继续接收其他用户的推送通知。为了注销,你需要存储 'registerDeviceToken' 方法返回的 tokenId,然后在注销前发送。如果你的应用程序没有实现登录/注销功能,你很可能永远不会需要调用此方法。
Swift
#!swift
IntelligenceManager.intelligence.identity.unregisterDeviceToken(withId: id, callback: { (error) -> Void in
if error != nil {
// Failed, handle error.
} else {
// Successfully unregistered, clear anything stored in the keychain.
}
})
Objective-C
#!objc
[[[INTIntelligenceManager intelligence] identity] unregisterDeviceTokenWithId:tokenId callback:^(NSError * _Nullable error) {
if (error != nil) {
// Failed, handle error.
} else {
// Successfully unregistered, clear anything stored in the keychain.
}
}];
‘unregisterDeviceTokenWithId’ 方法可以返回以下附加错误
- IdentityError.DeviceTokenNotRegisteredError:设备令牌未在 Intelligence 平台上注册。如果你尝试两次注销令牌,你会收到此错误,你应该将其视为成功的请求处理。