Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to develop Swift applications with websocket

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the knowledge of "how to develop Swift applications with websocket". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Let's take a look at our final results:

1. Create WebSocket with URLSession

With URLSessionWebSocketTask, it is very easy to create a WebSocket with URLSession. The five core operations of a WebSocket connection are described below.

First, open the connection:

Let urlSession = URLSession (configuration: .default) let webSocketTask = urlSession.webSocketTask (with: "wss://ws.finnhub.io?token=XYZ") webSocketTask.resume ()

Second, send a string or data

WebSocketTask.send (.string ("Hello")) {error in...}

Third, receive the response result message

WebSocketTask.receive {result in...}

Number 4, disconnect.

WebSocketTask.cancel (with: .goingAway, reason: nil)

Fifth, we can use the ping/pong mechanism to ensure that the connection remains active:

WebSocketTask?.sendPing {(error) in.} 2. Implement the real-time Bitcoin quotation interface based on SwiftUI + WebSocket

First, go to this website to generate an API KEY that can access Bitcoin quotes:

The following SwiftUI view contains a SF symbol picture and a text box showing the real-time price of bitcoin:

Import SwiftUIimport Combineimport Foundationstruct ContentView: View {@ ObservedObject var service = WebSocketService () var body: some View {VStack {Image (systemName: "bitcoinsign.circle.fill") .font (.system (size: 150)) .foreground Color (Color (red: 247255, green: 142255) Blue: 26 / 255) .padding () Text ("USD") .font (.largeTitle) .padding () Text (service.priceResult) .font (.system (size: 60))} .font { Self.service.connect ()}

PriceResult needs to be published from the ObservableObject class-- you can see it in the following WebSocketService.swift:

Class WebSocketService: ObservableObject {private let urlSession = URLSession (configuration: .default) private var webSocketTask: URLSessionWebSocketTask? Private let baseURL = URL (string: "wss://ws.finnhub.io?token=XYZ")! Let didChange = PassthroughSubject () @ Published var price: String = "" private var cancellable: AnyCancellable? = nil var priceResult: String = "" {didSet {didChange.send ()}} init () {cancellable = AnyCancellable (for: 0.5, scheduler: DispatchQueue.main) .removeDuplicates () .removeDuplicates (to:\. PriceResult On: self))}}

In the above code, we defined some properties and established the subscription in the init method. You need to replace XYZ with your own API KEY.

The operators used on Publisher are very important. We used Debounce to reduce the frequency of real-time updates and removeDuplicates to eliminate duplicate values.

To manually send changes to the SwiftUI view, the didChange.send () method can be triggered when the priceResult property is updated.

The other code to construct the WebSocketService class of WebSocket URLSession is as follows:

Class WebSocketService: ObservableObject {func connect () {stop () webSocketTask = urlSession.webSocketTask (with: baseURL) webSocketTask?.resume () sendMessage () receiveMessage ()} func stop () {webSocketTask?.cancel (with: .goingAway, reason: nil)} private func sendMessage () {let string = "{\" type\ ":\" subscribe\ " \ "symbol\":\ "BINANCE:BTCUSDT\"} "let message = URLSessionWebSocketTask.Message.string (string) webSocketTask?.send (message) {error in if let error = error {print (" WebSocket couldn't send message because:\ (error) ")}} private func receiveMessage () {webSocketTask?.receive {[weak self] result in switch result {case .failure (let error): print ("Error in receiving message:\ (error)") case .success (.string (let str)): do {let decoder = JSONDecoder () let result = try decoder.decode (APIResponse.self) From: Data (str.utf8) DispatchQueue.main.async {self?.price = "\ (result.data [0] .p)"} catch {print ("error is\ (error.localizedDescription)")} Self?.receiveMessage () default: print ("default")}

The following structural model is used to decode the response result of API:

Struct APIResponse: Codable {var data: [PriceData] var type: String private enum CodingKeys: String, CodingKey {case data, type}} struct PriceData: Codable {public var p: Float private enum CodingKeys: String, CodingKey {case p}}

Now run the application using the WatchOS simulator, which looks like this:

This is the end of the content of "how to develop Swift applications with websocket". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report