How to connect Socket in Swift 4

前端 未结 3 1582
时光取名叫无心
时光取名叫无心 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:14

    Is your URL secured under HTTPS? If it is not, that could be the problem, due to App Transport Security restrictions.

    See Info Plist Reference

    See also this post here.

    If that's not the problem. I'd suggest to check if your Socket version on both sides, server and client, are the same. Recently I had a problem because of that.

    Hope it helps!

    0 讨论(0)
  • 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!

    0 讨论(0)
  • try this Example:

     let manager = SocketManager(socketURL: URL(string: 
     "http://xxxxxxxxx.com")!, config: [.log(true), .compress])
     var socket = manager.defaultSocket
    
    socket.connect()
        socket.on(clientEvent: .connect) {data, ack in
            print("socket connected")
            self.gotConnection()
           }
        }
    
     func gotConnection(){
    
     socket.on("new message here") { (dataArray, ack) in
    
        print(dataArray.count)
    
         }
       }
    
    0 讨论(0)
提交回复
热议问题