FayeSwift 是一个简单的 Swift 客户端库,用于 Faye 发布/订阅消息服务器。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)")
}
didUnsubscribeFromChannel 在客户端从 Faye 通道取消订阅时调用。
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 许可证授权。