Integrate WebSocket iOS
Posted By : Vasu Saini | 30-Jun-2017
Today we will learn how to integrate web socket for live data updation in our iOS applications such as live chat etc .
Starscream is a powerful and simplest web socket which also has been used as parent library such as Stompclient use Starscream as parent library.
Step 1. Install pod 'Starscream', '~> 2.0.3' in the project in which you have required web socket.
Step 2 . After Installing web Socket in the project import Starscream in AppDelegate of your project.
import Starscream
Step 3. Add WebSocketDelegate in AppDelegate Class.
class AppDelegate: UIResponder, UIApplicationDelegate,WebSocketDelegate {
Step 4. Now Add all required Delegates in your class as follows
// MARK: Websocket Delegate Methods.
func websocketDidConnect(socket: WebSocket) {
print("websocket is connected")
}
func websocketDidDisconnect(socket: WebSocket, error: NSError?) {
if let e = error {
print("websocket is disconnected: \(e.localizedDescription)")
} else {
print("websocket disconnected")
}
}
func websocketDidReceiveMessage(socket: WebSocket, text: String) {
print("Received text: \(text)")
}
func websocketDidReceiveData(socket: WebSocket, data: Data) {
print("Received data: \(data.count)")
}
func pushSocket(){
if socket.isConnected{
socket.write(string: "Any Message You Want to Send")
}
else{
socket.connect()
socket.onConnect = {
self.socket.write(string: "Any Message You Want to Send")
}
}
}
Step 5. Now Create an Shared Instance of your app Utility Class as follows
let appDelegateSharedInstance = UIApplication.shared.delegate as! AppDelegate
Step 6. Now send the message to web Socket as Follows
appDelegateSharedInstance.pushSocket()
Step 7. Your message will be sent to socket server, if any message dispatched from server then it will be recieved in the delegate
websocketDidReceiveMessage
Step 8. Your can use this socket for live updation of data or live chat or such live tasks.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Vasu Saini
Vasu Saini is Passionate to deploy ideas into real world, Have zeal to learn new technologies. working as iOS Developer in Oodles Technologies. Sports Freak, Calisthenics ,Parkour, Love to play football, swimmer, athletics etc