测试已测试 | ✗ |
Lang语言 | SwiftSwift |
许可 | MIT |
Released上次发布 | 2017年1月 |
SwiftSwift 版本 | 3.0 |
SPM支持 SPM | ✓ |
由 Haris Amin 维护。
依赖 | |
Starscream | ~> 2.0 |
SwiftyJSON | ~> 3.1 |
Faye 发表-订阅消息服务器的一个简单的 Swift 客户端库。FayeObjC 在 Starscream Swift 网络套接字库之上实现,将在 Mac(待 Xcode 6 Swift 更新)和 iPhone 项目上运行。
它受到了在这个地方找到的 Objective-C 客户端的影响很大:FayeObjc
注意:对于 Swift 2.2,请使用 FayeSwift 0.2.0
FayeSwift 通过 CocoaPods 提供。要安装它,只需将以下行添加到您的 Podfile 中:
pod "FayeSwift"
Swift 包管理器兼容性即将到来
您可以打开到您的 Faye 服务器的连接。请注意,client
最好作为一个属性,以便您的代理可以保留。您可以通过对特定频道进行订阅来启动一个客户端。
client = FayeClient(aFayeURLString: "ws://:5222/faye", channel: "/cool")
client.delegate = self
client.connectToServer()
然后您还可以通过如下方式使用块处理器订阅附加频道
let channelBlock:ChannelSubscriptionBlock = {(messageDict) -> Void in
let text: AnyObject? = messageDict["text"]
println("Here is the Block message: \(text)")
}
client.subscribeToChannel("/awesome", block: channelBlock)
或者没有它们,让代理处理它们如下
self.client.subscribeToChannel("/delegates_still_rock")
连接后,还有一些可选的代理方法我们可以实现。
connectedToServer 在客户端连接到 Faye 服务器时立即调用。
func connectedToServer(client: FayeClient) {
println("Connected to Faye server")
}
connectionFailed 在客户端无法连接到 Faye 服务器时调用,无论是在初始连接还是在重试时。
func connectionFailed(client: FayeClient) {
println("Failed to connect to Faye server!")
}
disconnectedFromServer 在客户端从服务器断开连接时立即调用。
func disconnectedFromServer(client: FayeClient) {
println("Disconnected from Faye server")
}
didSubscribeToChannel 在向 Faye 频道订阅时调用。
func didSubscribeToChannel(client: FayeClient, channel: String) {
println("subscribed to channel \(channel)")
}
当客户取消订阅 Faye 通道时,会调用 didUnsubscribeFromChannel。
func didUnsubscribeFromChannel(client: FayeClient, channel: String) {
println("UNsubscribed from channel \(channel)")
}
当客户端无法订阅 Faye 通道时,会调用 subscriptionFailedWithError 方法。
func subscriptionFailedWithError(client: FayeClient, error: subscriptionError) {
println("SUBSCRIPTION FAILED!!!!")
}
当客户端从其已订阅的任何 Faye 通道接收到消息时,会调用 messageReceived。
func messageReceived(client: FayeClient, messageDict: NSDictionary, channel: String) {
let text: AnyObject? = messageDict["text"]
println("Here is the message: \(text)")
self.client.unsubscribeFromChannel(channel)
}
代理方法为您提供了简单处理来自服务器数据的方式,但您如何发布数据到 Faye 通道呢?
您可以通过调用 sendMessage 发送字典对象到通道。
client.sendMessage(["text": textField.text], channel: "/cool")
这是一个使用 NodeJS Faye 库的 Faye 服务器示例。如果您已安装 NodeJS,只需运行以下命令来安装该包
npm install
然后您可以使用如下方式启动 Faye 服务器
node faye_server.js
查看 FayeSwiftDemo 项目,了解如何设置简单的 Faye 服务器连接。
FayeSwift 至少需要 iOS 7/OSX 10.10 或更高版本。
FayeSwift 是基于 MIT 许可证的。