测试已测试 | ✓ |
Lang语言 | SwiftSwift |
许可证 | 定制 |
发布上次发布 | 2017 年 5 月 |
SwiftSwift 版本 | 3.1 |
SPM支持 SPM | ✗ |
依赖 | |
CryptoSwift | >= 0 |
Starscream | ~> 2.0.3 |
包含 Cogs Pub Sub API 的 Swift 客户端 SDK。
创建一个 PubSubOptions
并设置连接的选项和事件处理器。如果没有提供选项,将使用默认选项。
let options = PubSubOptions.defaultOptions
or
let options = PubSubOptions(url: url,
connectionTimeout: 30,
autoReconnect: true,
minReconnectDelay: 5,
maxReconnectDelay: 300,
maxReconnectAttempts: -1,
onNewSessionHandler: { (sessionUUID) in
print(sessionUUID)
},
onReconnectHandler: {
print("Session is restored")
},
onRawRecordHandler: { (record) in
print (record)
},
onMessageHandler: { (receivedMessage) in
print (receivedMessage)
},
onCloseHandler: { (error) in
if let err = error {
print(err.localizedDescription)
} else {
print("Session is closed")
}
},
onErrorHandler: { (error) in
print(error.localizedDescription)
},
onErrorResponseHandler: { (responseError) in
print("\(responseError.message) \n \(responseError.code)")
})
onNewSession
事件表示与此连接关联的会话不是一个恢复会话,因此此会话没有与之关联的订阅。如果之前有一个会话,并且连接被自动重连所替换,则不会恢复之前的会话,导致所有订阅丢失。
options.onNewSession = { sessionUUID in
print("New session \(sessionUUID) is opened."
}
当socket因为任何原因断开重连时,会触发onReconnect
事件。
options.onReconnect = {
print("Session is restored")
}
每当从服务器接收到原始记录时,都会触发onRawRecord
事件,无论是对请求的响应还是消息。这主要用于调试与服务器通信的问题。
options.onRawRecord = { (record) in
print (record)
}
每当socket从任何通道接收信息时,都会触发onMessage
事件。
options.onMessage = { (receivedMessage) in
print (receivedMessage)
}
在发生任何连接错误、发布失败或抛出异常时,会触发onError
事件。
options.onError = { (error) in
print(error.localizedDescription)
}
每当向用户发送带有错误状态码的消息时,会触发onErrorResponse
事件。
options.onErrorResponse = { (responseError) in
print("\(responseError.message) \n \(responseError.code)")
}
每当socket连接关闭时,会触发onClose
事件。
options.onClose = { (error) in
if let err = error {
print(err.localizedDescription)
} else {
print("Session is closed")
}
}
创建一个PubSubService
对象以获取连接句柄。创建的PubSubConnectionHandle
对象初始化并建立WebSocket连接。
let keys: [String] = ["read key", "write key", "admin key"]
let options = PubSubOptions(url: url,
connectionTimeout: 30,
autoReconnect: true,
minReconnectDelay: 5,
maxReconnectDelay: 300,
maxReconnectAttempts: -1,
onNewSessionHandler: { (sessionUUID) in
print(sessionUUID)
},
onReconnectHandler: {
print("Session is restored")
},
onRawRecordHandler: { (record) in
print (record)
},
onMessageHandler: { (receivedMessage) in
print (receivedMessage)
},
onCloseHandler: { (error) in
if let err = error {
print(err.localizedDescription)
} else {
print("Session is closed")
}
},
onErrorHandler: { (error) in
print(error.localizedDescription)
},
onErrorResponseHandler: { (responseError) in
print("\(responseError.message) \n \(responseError.code)")
})
let connection = PubSubService.connnect(keys: keys,
options: options)
这是对PubSubConnectionHandle
对象暴露的所有功能的总结以及它们的使用示例。
从服务器获取会话UUID。成功的结果包含与此连接相关联的UUID。
connection.getSessionUuid { outcome in
switch outcome {
case .pubSubSuccess(let uuid):
print("Session uuid \(uuid)")
case .pubSubResponseError(let error):
print(error)
}
}
将连接订阅到通道,提供一个将每个从该通道接收到的消息作为参数调用的处理程序。成功的结果包含订阅通道的列表。连接需要读取权限才能订阅通道。
connection.subscribe(channel: channel,
messageHandler: { (message) in
print("\(message.id) | \(message.message)")
}) { outcome in
switch outcome {
case .pubSubSuccess(let subscribedChannels):
print(subscribedChannels)
case .pubSubResponseError(let error):
print(error)
}
}
从特定通道取消订阅连接。成功的结果包含一个数组,其中包含未订阅的当前通道,其中包括刚刚取消订阅的通道。要取消订阅通道,连接需要读取权限。
connection.unsubscribe(channel: channel){ outcome in
switch outcome {
case .pubSubSuccess(let subscribedChannels):
print(subscribedChannels) //The list won't include the channel to unsubscribe from
case .pubSubResponseError(let error):
print(error)
}
}
取消连接对所有通道的订阅。成功的结果应该是一个空数组。要取消对所有通道的订阅,连接需要有读取权限。
connection.unsubscribeAll(){ outcome in
switch outcome {
case .pubSubSuccess(let subscribedChannels):
print(subscribedChannels)
// This is the list of channels to which we were subscribed prior to running this operation.
case .pubSubResponseError(let error):
print(error)
}
}
获取所有订阅。成功的结果包含一个数组,其中包含当前订阅的通道。
connection.listSubscriptions(){ outcome in
switch outcome {
case .pubSubSuccess(let subscribedChannels):
print(subscribedChannels)
case .pubSubResponseError(let error):
print(error)
}
}
向频道发布一条消息。连接必须具有写入权限才能成功发布消息。消息字符串限制为64KiB。超出此限制的消息会导致WebSocket连接终止。
connection.publish(channel: channel, message: messageText){ error in
print(error as Any)
}
向频道发布消息。成功结果包含已发布消息的UUID。
connection.publishWithAck(channel: channel, message: messageText){ outcome in
switch outcome {
case .pubSubSuccess(let messadeUuid):
print(messadeUuid)
case .pubSubResponseError(let error):
print(error)
}
}
断开连接。
connection.dropConnection()
通过关闭WebSocket关闭pub/sub连接句柄。
connection.close()
不需要设置服务,因为CogsSDK内部维护服务的一个单例实例。您需要确保您的客户端认证组件(访问密钥、客户端盐和客户端密钥)对每个请求都是可用的。
import CogsSDK
// Hex encoded access-key from one of your api keys in the Web UI.
let accessKey: String = "0000"
// Hex encoded client salt/secret pair acquired from /client_secret endpoint and
// associated with above access-key.
let clientSalt: String = "0000"
let clientSecret: String = "0000"
// Acquire the CogsSDK service singleton
cogsService = GambitService.sharedGambitService
此API路由用于向Cogs发送事件。
// This will be sent along with messages so that you can identify the event which
// "triggered" the message delivery.
let eventName: String = "my-event"
// The name of the namespace for which the event is destined.
let namespace: String = "my-namespace"
// The event attributes whose names and types should match the namespace schema.
let attributes: [String: AnyObject] = [
"uuid": "deadbeef-dead-beef-dead-beefdeadbeef"
]
// Assemble the event
let eventRequeset = GambitRequestEvent(
accessKey: accessKey,
clientSalt: clientSalt,
clientSecret: clientSecret,
eventName: eventName,
namespace: namespace,
attributes: attributes
)
// Send the event, and handle the response
cogsService.requestEvent(eventRequeset) { dat, rsp, err in
if let error = err {
// Handle error
}
else if let response = rsp as? NSHTTPURLResponse {
if response.statusCode == 200 {
if let data = dat {
do {
let json : JSON = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
let parsedResponse = try GambitResponseEvent(json: json)
// Handle message content
} catch {
// Handle JSON parse error
}
} else {
// Handle no response data
}
} else {
// Handle non-200 status code
}
}
}
此API路由用于将设备注册到命名空间内特定主题以接收推送通知。
// The iOS app identifier.
let platformAppId: String = "com.example.app"
// The app environment.
let environment: String = "production"
// The unique identifier for the device used to deliver APNS notifications.
let udid: String = "0000"
// The name of the namespace to which the device is registering for notifications
// on the specified topic.
let namespace: String = "my-namespace"
// The primary key attributes which identify the topic, whose names and types
// must match the namespace schema.
let pkAttributes: [String: AnyObject] = [
"uuid": "deadbeef-dead-beef-dead-beefdeadbeef"
]
let pushRequest = GambitRequestPush(
clientSalt: clientSalt,
clientSecret: clientSecret,
UDID: udid,
accessKey: accessKey,
attributes: pkAttributes,
environment: environment,
platformAppID: platformAppId,
namespace: namespace
)
// Send the push registration, and handle the response.
cogsService.registerPush(pushRequest) { dat, rsp, err in
if let error = err {
// Handle error
}
else if let response = rsp as? NSHTTPURLResponse {
if response.statusCode == 200 {
if let data = dat {
do {
let json : JSON = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
let parsedResponse = try GambitResponsePush(json: json)
// Handle message content
} catch {
// Handle JSON parse error
}
} else {
// Handle no response data
}
} else {
// Handle non-200 status code
}
}
}
此API路由用于取消注册设备,该设备之前已注册以获取特定命名空间/主题对的推送通知。
// The iOS app identifier.
let platformAppId: String = "com.example.app"
// The app environment.
let environment: String = "production"
// The unique identifier for the device used to deliver APNS notifications.
let udid: String = "0000"
// The name of the namespace from which the device is unregistering for
// notifications on the specified topic.
let namespace: String = "my-namespace"
// The primary key attributes which identify the topic, whose names and types
// must match the namespace schema.
let pkAttributes: [String: AnyObject] = [
"uuid": "deadbeef-dead-beef-dead-beefdeadbeef"
]
// Assemble the push de-registration request
let pushRequest = GambitRequestPush(
clientSalt: clientSalt,
clientSecret: clientSecret,
UDID: udid,
accessKey: accessKey,
attributes: pkAttributes,
environment: environment,
platformAppID: platformAppId,
namespace: namespace
)
// Send the push de-registration, and handle the response.
cogsService.unregisterPush(pushRequest) { dat, rsp, err in
if let error = err {
// Handle error
}
else if let response = rsp as? NSHTTPURLResponse {
if response.statusCode == 200 {
if let data = dat {
do {
let json : JSON = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
let parsedResponse = try GambitResponsePush(json: json)
// Handle message content
} catch {
// Handle JSON parse error
}
} else {
// Handle no response data
}
} else {
// Handle non-200 status code
}
}
}
此API路由用于根据其ID获取消息的完整内容。这是必要的,因为推送通知不传递整个消息内容,只有消息的ID。
// The ID of the message to be fetched.
let messageId: String = "00000000-0000-0000-0000-000000000000"
// The namespace of the message to be fetched.
let namespace: String = "my-namespace"
// The attributes identifying the topic of the message.
let pkAttributes: [String: AnyObject] = [
"uuid": "deadbeef-dead-beef-dead-beefdeadbeef"
]
// Assemble the message request.
let messageRequest = GambitRequestPush(
accessKey: accessKey,
clientSalt: clientSalt,
clientSecret: clientSecret,
token: messageId,
namespace: namespace,
attributes: pkAttributes
)
// Send request the message, and handle the response.
cogsService.message(messageRequest) { dat, rsp, err in
if let error = err {
// Handle error
}
else if let response = rsp as? NSHTTPURLResponse {
if response.statusCode == 200 {
if let data = dat {
do {
let json : JSON = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
let parsedResponse = try GambitResponseMessage(json: json)
// Handle message content
} catch {
// Handle JSON parse error
}
} else {
// Handle no response data
}
} else {
// Handle non-200 status code
}
}
}
Keys.plist
文件,并使用您的自己的密钥填充adminKey
、readKey
和writeKey
。CogsSDK_Tests
并选择要运行的测试类或单个测试Aviata Inc.
版权所有2016 Aviata Inc.
根据Apache License,版本2.0(“许可”)许可;除非按照适用的法律要求或经书面同意,否则不得使用此文件,但需遵守许可条款。您可以在以下位置获得许可副本:
https://apache.ac.cn/licenses/LICENSE-2.0
除非适用的法律要求或书面同意,否则根据本许可发布的软件按“原样”提供,不提供任何明示或暗示的担保或条件。有关权限和限制的特定语言,请参阅许可协议。