WWWebSocket

main

Wraps URLSession's iOS 13 webSocketTask() into an easy-to-use widget.
William-Weng/WWWebSocket

WWWebSocket

Swift-5.6 iOS-14.0 Swift Package Manager-SUCCESS LICENSE

  • Wraps URLSession's iOS 13 webSocketTask() into an easy-to-use widget.
  • 將URLSession的iOS 13的webSocketTask()包裝成簡單使用的小工具。

WWWebSocket

dependencies: [
    .package(url: "https://github.com/William-Weng/WWWebSocket.git", .upToNextMajor(from: "1.1.1"))
]

Function - 可用函式

函式 功能
connent(with:delegate:configuration:delegateQueue:) WebSocket連線 => 接收訊息
sendMessage(_:result:) 傳送訊息
cancel(with:reason:) 關閉連線

Example

import UIKit
import WWPrint
import WWWebSocket

final class ViewController: UIViewController {
    
    @IBOutlet weak var resultLabel: UILabel!
    
    private let url = "wss://demo.piesocket.com/v3/channel_123?api_key=VCXCEuvhGcBDP7XhiJJUDvR1e1D3eiVjgZ9VRiaV&notify_self"
    
    override func viewDidLoad() {
        super.viewDidLoad()
        connect(with: url)
    }
}

// MARK: - WWWebSocketDelegate
extension ViewController: WWWebSocketDelegate {
    
    func didOpenWithProtocol(_ protocol: String?) {
        wwPrint("connected => \(String(describing: `protocol`))")
    }
    
    func didCloseWith(_ closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) {
        wwPrint("disconnected => \(closeCode), \(String(describing: reason))")
    }
    
    func receiveMessageResult(_ result: Result<URLSessionWebSocketTask.Message, Error>) {
        
        switch result {
        case .failure(let error): wwPrint(error)
        case .success(let message):
            switch message {
            case .string(let string): self.resultLabel.text = string
            case .data(let data): wwPrint(data)
            @unknown default: break
            }
        }
    }
}

// MARK: - 小工具
private extension ViewController {
    
    /// [WebSocket連線](https://www.piesocket.com/websocket-tester)
    /// - Parameter url: String
    func connect(with url: String) {
        WWWebSocket.shared.connent(with: url, delegate: self)
    }
}

Description

  • Swift Tools 5.6.0
View More Packages from this Author

Dependencies

  • None
Last updated: Mon Apr 22 2024 07:39:28 GMT-0900 (Hawaii-Aleutian Daylight Time)