How to connect Socket in Swift 4

前端 未结 3 1599
时光取名叫无心
时光取名叫无心 2021-02-06 16:26

I want to connect my app to the socket here is the code :-

  import UIKit
  import SocketIO

 class SocketIOManager: NSObject {
static let manager = SocketManage         


        
3条回答
  •  天命终不由人
    2021-02-06 17:23

    You should make a shared property in your SocketIOManager class like this:

    static let shared = SocketIOManager()
    

    and then create init() like this:

        var socket: SocketIOClient!
    
        // defaultNamespaceSocket and swiftSocket both share a single connection to the server
        let manager = SocketManager(socketURL: URL(string: "http://localhost:3000")!, config: [.log(true), .compress])
    
        override init() {
            super.init()
    
            socket = manager.defaultSocket
            }
    

    and finally write your methods like this:

    func connectSocket() {
        let token = UserDefaults.standard.getAccessToken()
    
        self.manager.config = SocketIOClientConfiguration(
            arrayLiteral: .connectParams(["token": token]), .secure(true)
            )
            socket.connect()
    }
    
    func receiveMsg() {
        socket.on("new message here") { (dataArray, ack) in
    
            print(dataArray.count)
    
        }
    }
    

    and call your method like this:

    SocketIOManager.shared.connectSocket()
    

    The point is that you should make a strong reference to manager property in your viewController and static let shared = SocketIOManager() you do this for you!

提交回复
热议问题