CogsSDK 1.0.15

CogsSDK 1.0.15

测试已测试
Lang语言 SwiftSwift
许可证 定制
发布上次发布2017 年 5 月
SwiftSwift 版本3.1
SPM支持 SPM

CogsSDKCogsSDK 维护。



 
依赖
CryptoSwift>= 0
Starscream~> 2.0.3
 

CogsSDK 1.0.15

  • Aviata Inc.

描述

包含 Cogs Pub Sub API 的 Swift 客户端 SDK。

要求

  • iOS 9.0+
  • Xcode 8.0+
  • Swift 3.0+

安装

手动

  • 检出或下载 CogsSDK。
  • 在 Xcode 中打开 CogsSDK.xcworkspace。
  • 构建。
  • 导航到生成的数据文件夹,复制 CogsSDK.framework 并将其添加到您的项目中。

使用方法

Cogs Pub/Sub 选项

创建一个 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

onNewSession 事件表示与此连接关联的会话不是一个恢复会话,因此此会话没有与之关联的订阅。如果之前有一个会话,并且连接被自动重连所替换,则不会恢复之前的会话,导致所有订阅丢失。

options.onNewSession = { sessionUUID in
    print("New session \(sessionUUID) is opened."
}

事件:onReconnect

当socket因为任何原因断开重连时,会触发onReconnect事件。

options.onReconnect = {
    print("Session is restored")
}

事件:onRawRecord

每当从服务器接收到原始记录时,都会触发onRawRecord事件,无论是对请求的响应还是消息。这主要用于调试与服务器通信的问题。

options.onRawRecord = { (record) in
  print (record)
}

事件:onMessage

每当socket从任何通道接收信息时,都会触发onMessage事件。

options.onMessage = { (receivedMessage) in
    print (receivedMessage)
}

事件:onError

在发生任何连接错误、发布失败或抛出异常时,会触发onError事件。

options.onError = { (error) in
    print(error.localizedDescription)
}

事件:onErrorResponse

每当向用户发送带有错误状态码的消息时,会触发onErrorResponse事件。

options.onErrorResponse = { (responseError) in
  print("\(responseError.message) \n \(responseError.code)")
}

事件:onClose

每当socket连接关闭时,会触发onClose事件。

options.onClose = { (error) in
    if let err = error {
        print(err.localizedDescription)
    } else {
        print("Session is closed")
    }
}

Cogs Pub/Sub 服务

创建一个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)

Cogs Pub/Sub ConnectionHandle API

这是对PubSubConnectionHandle对象暴露的所有功能的总结以及它们的使用示例。

getSessionUuid(completion:)

从服务器获取会话UUID。成功的结果包含与此连接相关联的UUID。

connection.getSessionUuid { outcome in
    switch outcome {
        case .pubSubSuccess(let uuid):
            print("Session uuid \(uuid)")

        case .pubSubResponseError(let error):
            print(error)
    }
}

subscribe(channel:messageHandler:completion:)

将连接订阅到通道,提供一个将每个从该通道接收到的消息作为参数调用的处理程序。成功的结果包含订阅通道的列表。连接需要读取权限才能订阅通道。

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

unsubscribe(channel:completion:)

从特定通道取消订阅连接。成功的结果包含一个数组,其中包含未订阅的当前通道,其中包括刚刚取消订阅的通道。要取消订阅通道,连接需要读取权限。

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

unsubscribeAll(completion:)

取消连接对所有通道的订阅。成功的结果应该是一个空数组。要取消对所有通道的订阅,连接需要有读取权限。

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

listSubscriptions(completion:)

获取所有订阅。成功的结果包含一个数组,其中包含当前订阅的通道。

connection.listSubscriptions(){ outcome in
    switch outcome {
    case .pubSubSuccess(let subscribedChannels):
        print(subscribedChannels)

    case .pubSubResponseError(let error):
        print(error)
    }
}

publish(channel:message:errorHandler:)

向频道发布一条消息。连接必须具有写入权限才能成功发布消息。消息字符串限制为64KiB。超出此限制的消息会导致WebSocket连接终止。

connection.publish(channel: channel, message: messageText){ error in
    print(error as Any)
}

publishWithAck(channel:message:completion:)

向频道发布消息。成功结果包含已发布消息的UUID。

connection.publishWithAck(channel: channel, message: messageText){ outcome in
    switch outcome {
    case .pubSubSuccess(let messadeUuid):
        print(messadeUuid)

    case .pubSubResponseError(let error):
        print(error)
    }
}

dropConnection()

断开连接。

connection.dropConnection()

close()

通过关闭WebSocket关闭pub/sub连接句柄。

connection.close()

Gambit服务

不需要设置服务,因为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

requestEvent(_ gambitRequest:completionHandler:)

此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
    }
  }
}

registerPush(_ gambitRequest:completionHandler:)

此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
    }
  }
}

unregisterPush(_ gambitRequest:completionHandler:)

此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
    }
  }
}

message(_ gambitRequest:completionHandler:)

此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
    }
  }
}

Pub/Sub测试

  • 在Xcode的项目面板中找到“Tests”文件夹中的Keys.plist文件,并使用您的自己的密钥填充adminKeyreadKeywriteKey
  • 转到Xcode中的Test导航器(顶部的按钮中的菱形图标)
  • 展开CogsSDK_Tests并选择要运行的测试类或单个测试
  • 点击右侧的播放按钮

作者

Aviata Inc.

许可

版权所有2016 Aviata Inc.

根据Apache License,版本2.0(“许可”)许可;除非按照适用的法律要求或经书面同意,否则不得使用此文件,但需遵守许可条款。您可以在以下位置获得许可副本:

https://apache.ac.cn/licenses/LICENSE-2.0

除非适用的法律要求或书面同意,否则根据本许可发布的软件按“原样”提供,不提供任何明示或暗示的担保或条件。有关权限和限制的特定语言,请参阅许可协议。