反应式 Swift 使用来自 API 的实时数据 - 需要基本示例



我是 RxSwift 的新手,我正在寻找一个基本示例,说明如何在控制台中打印来自后端的实时数据流。我有一个后端,它每 1 秒流式传输一些虚拟数据,我可以通过 curl 请求看到它,我希望能够在控制台中自动观察和订阅并打印出来,请帮忙!

我假设您正在打开与服务器的套接字连接以接收实时数据。您可以使用 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
    }
}

相关内容

  • 没有找到相关文章

最新更新