BreinifyApi 2.0.20

BreinifyApi 2.0.20

测试已测试
语言语言 SwiftSwift
许可证 MIT
发行最后发布2022年2月
SPM支持SPM

Marco Recchioni维护。



  • Breinify Inc.

Breinify: Leading Temporal AI Engine

Breinify的API库

Version License Platform

功能:时间数据地理编码(反向)事件天气假日分析

此库利用Breinify的API,通过API端点提供诸如推送通知地理编码反向地理编码查找天气和事件确定假日等任务。每个端点提供不同的功能,将在以下段落中解释。此外,该文档还提供了对每个端点可用功能的具体示例。

推送通知:使用Breinify的时间驱动推送通知的目的是向单个应用程序用户(客户)发送高度动态和个性化的参与,而不是像传统细分市场所有人。

活动端点:该端点用于了解用户使用例如应用程序、移动应用程序或网页浏览器的使用模式和行为的例子。该端点通过Breinify仪表板提供分析和见解。

时间数据端点:该端点提供了解决时间信息(如时间戳、位置[纬度和经度或自由文本]或IP地址)到时间信息(例如时区、纪元、格式化日期、星期名称)的特性的功能,指定时间和位置的假日,城市的邮编、邻域、国家或县,指定时间和位置的活动的说明、规模、类型、天气的信息(例如描述、温度)。

入门指南

获取API密钥

首先,您需要一个有效的API密钥,您可以在https://www.breinify.com免费获取。在示例中,我们假设您拥有以下api密钥

938D-3120-64DD-413F-BB55-6573-90CE-473A

建议在利用iOS库时使用签名消息。签名消息确保请求已授权。要启用签名消息,请确保您的密钥启用了校验签名(有关更多信息,请参阅Breinify的API文档)。在本文档中,我们假设以下密钥按以下格式附加到API密钥并用于签名消息。

utakxp7sm6weo5gvk7cytw==

要求

  • iOS 9.0+
  • Xcode 12.1
  • AppCode 2020.2+
  • Swift 5.0

安装

如果您是CocoaPods新手并需要一些有关如何设置环境的信息(请始终使用CocoaPods的最新可用版本),请参阅以下链接链接

包含库

将以下内容添加到您的Pod文件中

...
pod 'BreinifyApi', '~> 2.0.17'
...

考虑Firebase库

如果使用Firebase消息支持(仅用于使用Firebase云消息服务发送推送通知),则需要包含以下Firebase库

...
pod 'Firebase/Core'
pod 'Firebase/Messaging'
...

权限

为了检索适当的信息,Breinify SDK 需要一些权限。在你的 info.plist 文件中,需要添加以下权限

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>api.breinify.com</key>
        <dict>
            <!--Include to allow subdomains-->
            <key>NSIncludesSubdomains</key>
            <true/>
            <!--Include to allow HTTP requests-->
            <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <!--Include to specify minimum TLS version-->
            <key>NSTemporaryExceptionMinimumTLSVersion</key>
            <string>TLSv1.1</string>
        </dict>
        <key>ip-api.com</key>
        <dict>
            <!--Include to allow subdomains-->
            <key>NSIncludesSubdomains</key>
            <true/>
            <!--Include to allow HTTP requests-->
            <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <!--Include to specify minimum TLS version-->
            <key>NSTemporaryExceptionMinimumTLSVersion</key>
            <string>TLSv1.1</string>
        </dict>
    </dict>
</dict>

库配置

每次使用库时,都需要使用正确的 API 密钥和密钥进行一次性配置。最佳位置是在 didFinishLaunchingWithOptions 方法中,如下所示

import BreinifyApi

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        /// constants for ApiKey and secret
        let validApiKey = "938D-3120-64DD-413F-BB55-6573-90CE-473A"
        let validSecret = "utakxp7sm6weo5gvk7cytw=="

        Breinify.initialize(apiKey: validApiKey, secret: validSecret)
        return true
    }

使用后清理

当不再使用库时,建议清理并释放持有的资源。为此,使用 Breinify.applicationWillTerminate() 方法。添加对 applicationWillTerminate 方法的调用,如下所示

func applicationWillTerminate(_ application: UIApplication) {
        Breinify.applicationWillTerminate()
}

活动:选择使用示例

使用 /activity 端点来跟踪应用的、应用程序或站点的使用情况。有多个库可用于不同的系统(例如,Node.jsAndroidJavaJavaScriptRubyPHPPython)。

发送登录信息

示例演示了如何发送登录活动,读取请求数据。通常,活动添加到应用程序流程中的有趣测量点(例如 loginaddToCartpageVisit)。端点通过 Breinify 控制台提供分析和见解。

当用户信息可用时,只要在第一个活动开始之前,立即添加 Breinify.setUserInfo(...)

// create a user you're interested in
Breinify.setUserInfo(firstName: "Fred", 
                     lastName: "Feuerstein",
                     phone: "+1223344556677",
                     email: "[email protected]")

发送页面访问活动

通过以下 4 个步骤发送一个活动:

  1. 创建与活动类型相关的额外数据
  2. 使用活动类型和额外的标签调用活动端点
// create additional activity type related data 
let tagsDic = [String: Any]()
tagsDic["pageId"] = "userDetailsPage" as Any
 
// invoke activity call
Breinify.sendActivity(BreinActivityType.PAGE_VISIT.rawValue, tagsDic: tagsDic)

TemporalData:选择的用法示例

使用 /temporalData 端点将您的临时数据转换为临时信息,即使用如 当前天气即将到来的假日地区和全球事件时区 以及地理编码和逆地理编码等信息丰富您的临时数据。

获取用户信息

有时需要获取有关应用程序用户的一些更多信息,例如,为了提高可用性和增强用户体验,正确处理时间依赖数据,添加基于地理位置的服务或提高服务质量。可以通过调用使用 Breinify.temporalData(...) 方法或执行 BreinTemporalData 实例来轻松检索客户端信息,即调用 /temporaldata 端点

do {   
   try Breinify.temporalData({
      // success
      (result: BreinResult) -> Void in
                
      if let holiday = result.get("holidays") {
         print("Holiday is: \(holiday)")
      }
      if let weather = result.get("weather") {
         print("Weather is: \(weather)")
      }
      if let location = result.get("location") {
         print("Location is: \(location)")
      }
      if let time = result.get("time") {
         print("Time is: \(time)")
      }
   })
   } catch {
     print("Error")
}

返回的结果包含关于时间、位置、天气、假日和事件的详细信息。有关返回值的详细示例,请参阅 此处

Sample output of the user information.
利用一些常用功能可能得到的样本输出。

地理编码(将文本解析为位置)

有时,需要将文本表示转换为特定的地理位置。文本表示可能是结构化的,也可能部分是非结构化的,例如,文本表示 the Big Apple 被认为是非结构化的,而一个结构化位置可能是,例如,{ city: 'Seattle', state: 'Washington', country: 'USA' }。也可以传入部分信息,然后让系统尝试解析/完成位置,例如,{ city: 'New York', country: 'USA' }

	do {
	   let breinTemporalData = BreinTemporalData()
	           .setLocation(freeText: "The Big Apple")
	            
	   try Breinify.temporalData(breinTemporalData, {           
	          (result: BreinResult) -> Void in
	        
             let breinLocationResult = BreinLocationResult(result)
             print("Latitude is: \(breinLocationResult.getLatitude())")
             print("Longitude is: \(breinLocationResult.getLongitude())")
             print("Country is: \(breinLocationResult.getCountry())")
             print("State is: \(breinLocationResult.getState())")
             print("City is: \(breinLocationResult.getCity())")
             print("Granularity is: \(breinLocationResult.getGranularity())")
	        })
	  } catch {
	       print("Error")
	  }

这将导致以下结果

Latitude is: 40.7614927583
Longitude is: -73.9814311179
Country is: US
State is: NY
City is: New York

或者显示为苹果地图(Apple Map)的结果

Sample Map of the results from the geocoding requests.
利用反地理编码请求结果生成的地图输出

反地理编码(获取例如城市、邻里或邮编的GeoJson)

该库还提供反地理编码功能。拥有特定的地理位置,并解析坐标到特定的城市或邻里(即邻里、城市、州、国家,以及可选的GeoJson形状)。

如果对事件感兴趣,可能的请求可能如下所示

do {
   let breinTemporalData = BreinTemporalData()
         .setLatitude(37.7609295)
         .setLongitude(-122.4194155)
         .addShapeTypes(["CITY"]) 
  
   try Breinify.temporalData(breinTemporalData, {
      (result: BreinResult) -> Void in
      print("Api Success : result is:\n \(result)")

     // Events
     let breinEventResult = BreinEventResult(result)
     breinEventResult.getEventList().forEach { (entry) in

     let eventResult = BreinEventResult(entry)
     print("Starttime is: \(eventResult.getStartTime())")
     print("Endtime is: \(eventResult.getEndTime())")
     print("Name is: \(eventResult.getName())")
     print("Size is: \(eventResult.getSize())")

     let breinLocationResult = eventResult.getLocationResult()
     print("Latitude is: \(breinLocationResult.getLatitude())")
     print("Longitude is: \(breinLocationResult.getLongitude())")
     print("Country is: \(breinLocationResult.getCountry())")
     print("State is: \(breinLocationResult.getState())")
     print("City is: \(breinLocationResult.getCity())")
     print("Granularity is: \(breinLocationResult.getGranularity())")
     }
   } 

推送通知:选定使用示例

让我们将Breinify的推送通知集成的iOS App中。点击这个链接了解如何配置您的应用程序以接收推送通知。

使用APNS服务配置库

如果推送通知来自APNS,请在您的 AppDelegate.swift 文件中添加以下声明

import BreinifyApi

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { 
        var userInfoDic = [String: String]()
        userInfoDic["firstName"] = "Fred"
        userInfoDic["lastName"] = "Firestone"
        userInfoDic["phone"] = "+1223344556677"
        userInfoDic["email"] = "[email protected]" // mandatory

        let apnsToken = Breinify.retrieveDeviceToken(deviceToken)

        Breinify.initWithDeviceTokens(apnsToken: apnsToken,
                        fcmToken: nil,
                        userInfo: userInfoDic)
             
   }

使用Firebase云消息服务配置库

如果推送通知来自Firebase云消息服务,请在您的 AppDelegate.swift 文件中添加以下声明

import Firebase
import BreinifyApi

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        // Firebase Message to retrieve the token
        Messaging.messaging().token { token, error in
            if let error = error {
                print("Error fetching FCM registration token: \(error)")
            } else if let token = token {
                print("FCM registration token: \(token)")

                var userInfoDic = [String: String]()
                userInfoDic["firstName"] = "Fred"
                userInfoDic["lastName"] = "Firestone"
                userInfoDic["phone"] = "+1223344556677"
                userInfoDic["email"] = "[email protected]" // mandatory

                let apnsToken = Breinify.retrieveDeviceToken(deviceToken)

                Breinify.initWithDeviceTokens(apnsToken: apnsToken,
                        fcmToken: token,
                        userInfo: userInfoDic)
         }
      }
   }

集成

在iOS应用程序中使用Breinify推送通知非常简单。Breinify API可以无缝集成到iOS应用程序生命周期中。只需在didReceiveRemoteNotification生命周期函数中调用相应的Breinify函数。

请将以下语句添加到您的代理Swift文件中(例如AppDelegate.swift

import BreinifyApi

方法 didReceiveRemoteNotification

存在两个名为didReceiveRemoteNotification的不同方法,需要通过将userInfo发送到Breinify SDK来增强,如下所示

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
   // inform the Breinify API      
   Breinify.didReceiveRemoteNotification(userInfo)
   completionHandlerUIBackgroundFetchResult.newData)  
}

以及这个不带completionHandler参数的方法。

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
  Breinify.didReceiveRemoteNotification(userInfo)     
}

通知示例屏幕

当应用配置为使用富文本通知时,Breinify引擎将触发一个通过Apple通知服务发送给用户的推送通知。

Sample output of the user information.
将会显示的通知。

如果用户对此特定通知进行了响应,还可能会出现更详细的对话框,具体取决于应用是否已配置为使用富文本通知。

Sample output of the user information.
包含更多信息的详细通知。

这是一个示例,用于显示地图。还可以考虑其他媒体内容(例如图像、视频)。

应用功能

位置数据

如果您的应用在Info.plist文件中配置了相应的属性,Breinify SDK可以提供当前的位置数据。只需添加以下位置权限

<key>NSLocationAlwaysUsageDescription</key>
<string>Please allow this app to provide location data.</string>
    
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Please allow this app to provide location data.</string>
    
<key>NSLocationUsageDescription</key>
<string>Please allow this app to provide location data.</string>
    
<key>NSLocationWhenInUseUsageDescription</key>
<string>Please allow this app to provide location data.</string>

传输安全

Breinify SDK将通过TCP发送信息。这需要通过Info.plist文件中的适当条目启用,如下所示

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

更多信息链接

要了解Breinify API的所有功能,请参阅