How can I use SocketRocket in a Swift Project?

2.9k Views Asked by At

I'm new in iOS programming and still learning Swift. I'm trying to use SocketRocket library https://github.com/facebook/SocketRocket in a Swift Project in order to connect to my Web Server, created using MAMP, through Web Sockets. I know that there is Starscream https://github.com/daltoniam/Starscream ready to use in Swift but it gives errors and I cannot make it work as I explained here: How to fix "websocket is disconnected: Invalid HTTP upgrade" error using Starscream

SocketRocket is written in Objective-C and I don't understand it, tried to look the documentation but I don't know how to translate it into Swift and implementing its methods in my project. Already installed SocketRocket using Cocoapods. So it doesn't need the header-bridging file because I used 'use_frameworks!' in the podfile.

ViewController.swift file:

import UIKit
import SocketRocket

class ViewController: UIViewController, SRWebSocketDelegate { //ERROR: Type 'ViewController' does not conform to protocol 'SRWebSocketDelegate' Do you want to add protocol stubs?
    
    var urlRequest = NSURLRequest(URL: NSURL(string: "http://host.com")) //EROOR: Cannot convert value of type 'NSURL?' to expected argument type 'URL' Insert ' as! URL'
    
    var socket = SRWebSocket(URLRequest: urlRequest)
    
    //let socket = SRWebSocket(url: "ws://localhost:8888")

    override func viewDidLoad() {
        super.viewDidLoad()
        
        socket.open()
        socket.send()
        socket.close()
    }
    
    func webSocketDidOpen(webSocket: SRWebSocket!) {
        print("socket opened");
    }
    
    func webSocket(webSocket: SRWebSocket!, didCloseWithCode code: Int, reason: String!, wasClean: Bool) {
        print("code: \(code) reason:\(reason) ");
    }
    
    func webSocket(webSocket: SRWebSocket!, didFailWithError error: NSError!) {
        print("error: \(error)");
    }
    
    func webSocket(webSocket: SRWebSocket!, didReceiveMessage message: AnyObject!) {
        print("received message")
    }
}

This is the code I tried to write... But there are errors as shown in the comments. Hope you guys could help me. Thanks!!! :)

1

There are 1 best solutions below

6
Vikash Sinha On

Hi Cristian, You can use " pod 'Socket.IO-Client-Swift' " also which uses Starscream.

For documentation you can look here also. Socket.IO-Client-Swift

    private var socket: SocketIOClient?
    private var manager: SocketManager?


    private func initializeSocket() {

    self.manager = SocketManager(socketURL:  URL(string: self.baseUrlForSocket)!, config: [.log(true), .forceNew(true), .reconnectAttempts(10), .reconnectWait(6000), .connectParams(["authorization": authKey]), .forceWebsockets(true), .compress])

    self.socket = manager?.defaultSocket
 }

Here baseUrlForSocket is the socket url which you have been provided and authKey is the authorization value.

In case of any concern, please let me know.