我是新来RxSwift和我正在寻找如何在控制台实时数据从后端流打印一个基本的例子。我有一个是流一些虚拟的数据每隔1秒后台,我可以用卷曲的要求中看到它,我希望能够观察和订阅,并打印出来在控制台自动,请帮忙!
我假设你正在打开,以便接收实时数据的套接字连接到服务器。您可以使用RxWebSocket来处理这个数据流。有在文件/自述文件API的例子。
https://github.com/daltoniam/Starscream/tree/master/examples/SimpleTest/SimpleTest
import UIKit
import Starscream
class ViewController: UIViewController, WebSocketDelegate {
var socket: WebSocket!
@IBOutlet weak var label: UILabel!
@IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
var request = URLRequest(url: URL(string: "wss://echo.websocket.org")!)
request.timeoutInterval = 5
socket = WebSocket(request: request)
socket.delegate = self
socket.connect()
}
// MARK: Websocket Delegate Methods.
func websocketDidConnect(socket: WebSocketClient) {
print("websocket is connected")
}
func websocketDidDisconnect(socket: WebSocketClient, error: Error?) {
if let e = error as? WSError {
print("websocket is disconnected: \(e.message)")
} else if let e = error {
print("websocket is disconnected: \(e.localizedDescription)")
} else {
print("websocket disconnected")
}
}
func websocketDidReceiveMessage(socket: WebSocketClient, text: String) {
self.label.text = text
print("Received text: \(text)")
}
func websocketDidReceiveData(socket: WebSocketClient, data: Data) {
print("Received data: \(data.count)")
}
// MARK: Write Text Action
@IBAction func send(_ sender: UIButton) {
socket.write(string: "Hello \(textField.text!)")
}
// MARK: Disconnect Action
@IBAction func disconnect(_ sender: UIBarButtonItem) {
if socket.isConnected {
sender.title = "Connect"
socket.disconnect()
} else {
sender.title = "Disconnect"
socket.connect()
}
}
}
extension URL {
init(staticString string: StaticString) {
guard let url = URL(string: "\(string)") else {
preconditionFailure("Invalid static URL string: \(string)")
}
self = url
}
}