Swift background websocket by Starscream

416 Views Asked by At

I am a rookie in iOS, here I want to make a background WebSocket to deal with all of the events from the server.

import UIKit
import Starscream

class WebSocketLink: WebSocketDelegate{
    
    var isConnected:Bool = false
    
    func connect(){
        
        var request = URLRequest(url: URL(string: "\(WEBSOCKET_HOST)")!)
        request.timeoutInterval = 5
        request.setValue("sessionid=\(ACCESS_TOKEN)", forHTTPHeaderField: "Cookie")
        SOCKET = WebSocket(request: request)
        SOCKET?.delegate = self
        SOCKET?.connect()
        
    }
    
    func disconnect() {
        SOCKET?.disconnect()
    }
    
    func didReceive(event: WebSocketEvent, client: WebSocket) {
        
        switch event{
        case .connected(let headers):
            isConnected = true
            print("websocket is connected: \(headers)")
        case .disconnected(let reason, let code):
            isConnected = false
            print("websocket is disconnected: \(reason) with code: \(code)")
        case .text(let string):
            print("Received text: \(string)")
        case .binary(let data):
            print("Received data: \(data.count)")
        case .ping(_):
            break
        case .pong(_):
            break
        case .viabilityChanged(_):
            break
        case .reconnectSuggested(_):
            break
        case .cancelled:
            isConnected = false
        case .error(let error):
            isConnected = false
            print(error ?? "x")
        }
    }
    
}

Here the SOCKET is a global variable:

var SOCKET:WebSocket? = nil

And I connect WebSocket in the App init function:

init(){

   let link = WebSocketLink()
   link.connect()

}

Then the application cannot print anything in didReceive function. I have already tested that WebSocket is connected and it can send and receive(by javascript test code). How can I receive the data from the server by didReceive function? Or any better way to make a background websocket to deal with all events from the server? Thank you in advance!!!!

0

There are 0 best solutions below