Skip to content

Instantly share code, notes, and snippets.

@dkan
Created January 6, 2015 00:57
Show Gist options
  • Save dkan/259ceda7895d8c658cbf to your computer and use it in GitHub Desktop.
Save dkan/259ceda7895d8c658cbf to your computer and use it in GitHub Desktop.
Socket Manager
import Foundation
class SocketManager: NSObject, SRWebSocketDelegate {
let kSocketUrl: NSURL = NSURL(string: "wss://narwhal-sock.herokuapp.com/")!
var connectionAttempts: Int = 0
var isConnected: Bool = false
var ws: SRWebSocket?
class var sharedInstance: SocketManager {
struct Static {
static var instance: SocketManager = SocketManager()
}
return Static.instance
}
func openWebsocket() {
closeWebsocket()
let request: NSURLRequest = NSURLRequest(URL: kSocketUrl)
ws = SRWebSocket(URLRequest: request)
if ws != nil {
ws!.delegate = self
ws!.open()
}
}
func closeWebsocket() {
isConnected = false
if ws != nil {
ws?.close()
ws!.delegate = nil
ws = nil
}
}
// event "message", takes "content_type", "body", "lat", "lon", "group_id"
func sendSocketEvent(event: String,
params: Dictionary<String, AnyObject>) {
if self.isConnected {
let writer: SBJson4Writer = SBJson4Writer()
ws!.send(writer.stringWithObject(params))
} else {
println("not connected")
}
}
func reconnect() {
isConnected = false
connectionAttempts += 1
if connectionAttempts < 6 {
Helper.delay(2, closure: {
self.openWebsocket()
})
} else {
connectionAttempts = 0
let notification: NSNotification = NSNotification(name: "SocketNetworkErrorNotification",
object: nil,
userInfo: nil)
NSNotificationCenter.defaultCenter().postNotification(notification)
}
}
// MARK: SRWebSocket delegate methods
func webSocket(webSocket: SRWebSocket!,
didReceiveMessage message: AnyObject!) {
println("didReceiveMessage", webSocket, message)
var error: NSError?
let data: NSData = message.dataUsingEncoding(NSUTF8StringEncoding)!
let json: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &error) as NSDictionary
let type: String = json["type"] as String!
if type == "auth" {
if json["auth"] as Int == 1 {
let currentUser: ServerContact = ServerContact(contact: json["user"] as NSDictionary)
UserDefaultsWrapper.save("currentUser", object: currentUser)
} else {
// Auth Error alert
}
} else if type == "message" {
let notification: NSNotification = NSNotification(name: "ReceivedMessageNotification",
object: nil,
userInfo: json)
NSNotificationCenter.defaultCenter().postNotification(notification)
} else if type == "status" {
let status: NSDictionary = json["status"] as NSDictionary
StatusManager.updateOnline((status["user_id"] as String!), status: (status["status"] as String!))
}
}
func webSocketDidOpen(webSocket: SRWebSocket!) {
println("didOpen", webSocket)
connectionAttempts = 0
isConnected = true
let token: String? = Helper.authToken()
if token != nil {
self.sendSocketEvent("token", params: ["token": token!])
ws!.sendPing(nil)
} else {
ws?.close()
}
}
func webSocket(webSocket: SRWebSocket!,
didCloseWithCode code: Int,
reason: String!,
wasClean: Bool) {
println("didClose", code, reason, wasClean)
reconnect()
}
func webSocket(webSocket: SRWebSocket!,
didFailWithError error: NSError!) {
println("didFailWithError", error)
reconnect()
}
func webSocket(webSocket: SRWebSocket!,
didReceivePong pongPayload: NSData!) {
Helper.delay(10.0, closure: {
if self.isConnected {
self.ws!.sendPing(nil)
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment