|
| 1 | +// |
| 2 | +// WebSocketService.swift |
| 3 | +// |
| 4 | +// |
| 5 | +// Created by Fernando Fernandes on 02.01.24. |
| 6 | +// |
| 7 | + |
| 8 | +import Foundation |
| 9 | + |
| 10 | +#warning("TODO: Observable, propagate received messages") |
| 11 | +public class WebSocketService { |
| 12 | + public var session: URLSession = .init(configuration: .default) |
| 13 | + |
| 14 | + private let urlString: String |
| 15 | + private let token: String |
| 16 | + private let clientId: String |
| 17 | + |
| 18 | + private var webSocketTask: URLSessionWebSocketTask? |
| 19 | + |
| 20 | + public init(urlString: String, |
| 21 | + token: String, |
| 22 | + clientId: String) throws { |
| 23 | + self.urlString = urlString |
| 24 | + self.token = token |
| 25 | + self.clientId = clientId |
| 26 | + |
| 27 | + try initializeWebSocket() |
| 28 | + receiveMessage() |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +// MARK: - Interface |
| 33 | + |
| 34 | +public extension WebSocketService { |
| 35 | + |
| 36 | + #warning("TODO: handle received messages as models, throw errors?") |
| 37 | + func receiveMessage() { |
| 38 | + webSocketTask?.receive { result in |
| 39 | + switch result { |
| 40 | + case .success(let message): |
| 41 | + switch message { |
| 42 | + case .string(let text): |
| 43 | + print("Received string: \(text)") |
| 44 | + case .data(let data): |
| 45 | + print("Received data: \(data)") |
| 46 | + @unknown default: |
| 47 | + fatalError() |
| 48 | + } |
| 49 | + |
| 50 | + // Listen for the next message. |
| 51 | + self.receiveMessage() |
| 52 | + |
| 53 | + case .failure(let error): |
| 54 | + print("Error in receiving message: \(error)") |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +// MARK: - Private |
| 61 | + |
| 62 | +private extension WebSocketService { |
| 63 | + func initializeWebSocket() throws { |
| 64 | + let webSocketURL = try createWebSocketURL() |
| 65 | + webSocketTask = session.webSocketTask(with: webSocketURL) |
| 66 | + webSocketTask?.resume() |
| 67 | + } |
| 68 | + |
| 69 | + #warning("TODO: remove this logic from here, this should be done previously") |
| 70 | + func createWebSocketURL() throws -> URL { |
| 71 | + let fullURL = "\(urlString)?token=\(token)&connectId=\(clientId)" |
| 72 | + guard let url = URL(string: fullURL) else { |
| 73 | + throw SwiftTraderWebSocketError.invalidWebSocketURL(urlString: fullURL) |
| 74 | + } |
| 75 | + return url |
| 76 | + } |
| 77 | +} |
0 commit comments