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!!! :)