5

I am in trouble how to implement websocket function to my swift code.

I have completed a server implementation and another javascript client. They are working well. So, I believe websocket server is not wrong.

But if I write the code in swift, it don't work. No error happen and no message is shown on the console.

Here is my swift code.

import UIKit
import SocketIO
class ChatViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate {
 @IBOutlet weak var tableView: UITableView!
 var bottomView: ChatRoomInputView!
 var chats: [ChatEntity] = []
 var socket: SocketIOClient!
 override func viewDidLoad() {
 super.viewDidLoad()
 tableView.delegate = self
 tableView.dataSource = self
 // Initialize WebSocket
 let manager = SocketManager(socketURL: URL(string: "http://example.com:8081")!, config: [.log(true), .compress])
 socket = manager.defaultSocket
 socket.on(clientEvent: .connect) {data, ack in
 print("socket connected")
 }
 socket.on("server_to_client") {[weak self] data, ack in
 print ("get Massage!!!")
 }
 socket.connect()
 socket.emit("join_room", with: [getRegistrationId()])
 socket.emit("client_to_server", with: ["ack_client"])
 setupUI()
 }
 override func didReceiveMemoryWarning() {
 super.didReceiveMemoryWarning()
 }
 override func viewWillDisappear(_ animated: Bool) {
 super.viewWillDisappear(animated)
 }
 override func viewWillAppear(_ animated: Bool) {
 super.viewWillAppear(animated)
 }
 override var canBecomeFirstResponder: Bool {
 return true
 }
 override var inputAccessoryView: UIView? {
 return bottomView
 }
 func setupUI() {
 self.view.backgroundColor = UIColor(red: 113/255, green: 148/255, blue: 194/255, alpha: 1)
 tableView.backgroundColor = UIColor(red: 113/255, green: 148/255, blue: 194/255, alpha: 1)
 tableView.separatorColor = UIColor.clear
 tableView.estimatedRowHeight = 10000
 tableView.rowHeight = UITableViewAutomaticDimension
 tableView.allowsSelection = false
 tableView.keyboardDismissMode = .interactive
 tableView.register(UINib(nibName: "YourChatViewCell", bundle: nil), forCellReuseIdentifier: "YourChat")
 tableView.register(UINib(nibName: "MyChatViewCell", bundle: nil), forCellReuseIdentifier: "MyChat")
 self.bottomView = ChatRoomInputView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 60))
 bottomView.chatTextField.delegate = self
 bottomView.textSendButton.addTarget(self, action: #selector(self.chatTextSendButton(_:)), for: .touchUpInside)
 }
 func numberOfSections(in tableView: UITableView) -> Int {
 return 1
 }
 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
 return self.chats.count
 }
 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
 let chat = self.chats[indexPath.row]
 if chat.isMyChat() {
 let cell = tableView.dequeueReusableCell(withIdentifier: "MyChat") as! MyChatViewCell
 cell.clipsToBounds = true
 // Todo: isRead
 cell.updateCell(text: chat.text, time: chat.time, isRead: true)
 return cell
 } else {
 let cell = tableView.dequeueReusableCell(withIdentifier: "YourChat") as! YourChatViewCell
 cell.clipsToBounds = true
 cell.updateCell(text: chat.text, time: chat.time, pic: RemoshinData.getDoctorPic())
 return cell
 }
 }
 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
 print(indexPath)
 }
 func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
 return 10
 }
 func textFieldShouldReturn(_ textField: UITextField) -> Bool {
 textField.resignFirstResponder()
 return true
 }
 func textFieldShouldClear(_ textField: UITextField) -> Bool {
 return true
 }
 func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
 textField.inputFieldBorderBottom(color: Utils.getColor(),
 x: textField.center.x,
 y: textField.center.y,
 w: textField.frame.size.width,
 h: textField.frame.size.height)
 bottomView.chatTextField = textField
 return true
 }
 func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
 textField.inputFieldBorderBottom(color: UIColor.lightGray,
 x: textField.center.x,
 y: textField.center.y,
 w: textField.frame.size.width,
 h: textField.frame.size.height)
 return true
 }
 @objc func chatTextSendButton(_ sender: AnyObject) {
 let chatText = bottomView.chatTextField.text!
 if (chatText != "") {
 let _mainViewController = MainViewController()
 let jsonData = _mainViewController.sendChatText(_registration_id: getRegistrationId(), _chat_text: chatText)
 if(jsonData["status"].string! == "success") {
 socket.emit("client_to_server", with: ["update_chat"])
 let chat = ChatEntity(text: jsonData["chat_text"].string!, time: "", userType: .I)
 chats.append(chat)
 tableView.reloadData()
 bottomView.chatTextField.text = ""
 }
 }
 }
}

I want to see "socket connected" message on my console when the app run. I think the socket is something wrong. But I have no idea what is wrong because no error message found. And I doubt if I need some setting in my info.plist. But, I don't make sense how to write.

Please give me some advice?

Myst
19.4k3 gold badges52 silver badges70 bronze badges
asked Apr 27, 2018 at 12:16
5
  • here is the answer stackoverflow.com/questions/50001818/… just don't pass token in your case Commented Apr 27, 2018 at 12:51
  • There is no line on the console. No message is displayed. Commented Apr 27, 2018 at 12:51
  • are you review my code @KazzzStudio? you just need to set your manager object in global scope Commented Apr 27, 2018 at 12:56
  • Yes, I did. I can get the message when I tried to connect to my websocket server.. Commented Apr 27, 2018 at 13:00
  • Please note that socket.io is not the same as WebSockets (although socket.io might use WebSockets internally). Commented Apr 27, 2018 at 14:56

1 Answer 1

4

socket.io-client-swift

var manager:SocketManager!
var socketIOClient: SocketIOClient!
override func viewDidLoad() {
 super.viewDidLoad()
 // Do any additional setup after loading the view, typically from a nib.
 ConnectToSocket()
}
func ConnectToSocket() {
 manager = SocketManager(socketURL: URL(string: "your url")!, config: [.log(true), .compress])
 socketIOClient = manager.defaultSocket
 socketIOClient.on(clientEvent: .connect) {data, ack in
 print(data)
 print("socket connected")
 }
 socketIOClient.on(clientEvent: .error) { (data, eck) in
 print(data)
 print("socket error")
 }
 socketIOClient.on(clientEvent: .disconnect) { (data, eck) in
 print(data)
 print("socket disconnect")
 }
 socketIOClient.on(clientEvent: SocketClientEvent.reconnect) { (data, eck) in
 print(data)
 print("socket reconnect")
 }
 socketIOClient.connect()
}

Update

In your case: SocketManager: Manager is being released

Sockets created through the manager are retained by the manager. So at the very least, a single strong reference to the manager must be maintained to keep sockets alive.

["Got unknown error from server Welcome to socket.io."]

  1. Check socket.io version on both server and client side, mismatch of both may be cause of this error
  2. Add an "App Transport Security Settings" key in info.plist (Dictionary type) and sub key "Allow Arbitrary Loads" (boolean type) with YES value.
answered Apr 27, 2018 at 12:39
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for an advice. I tried your code And I got the following error message. ["Got unknown error from server Welcome to socket.io."] socket error. I have no idea what is wrong because another client(javascript) connect correctly.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.