Socket.io for swift4 ios [英] Socket.io for swift4 ios

查看:362
本文介绍了Socket.io for swift4 ios的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了如何在我的swift代码中实现websocket函数的问题。

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

我已经完成了服务器实现和另一个javascript客户端。
他们运作良好。
所以,我相信websocket服务器没有错。

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

但是如果我在swift中编写代码,它就不起作用了。没有错误发生,控制台上没有显示任何消息。

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

这是我的快捷代码。

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 = ""
            }
        }
    }
}

我想在应用程序运行时在我的控制台上看到socket connected消息。我认为socket是错误的。但我不知道出了什么问题,因为没有找到错误信息。我怀疑我的info.plist中是否需要一些设置。但是,我怎么写都没有意义。

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.

请给我一些建议?

推荐答案

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()
}

更新

在您的情况下: SocketManager:Manager正在发布

管理员保留通过管理器创建的套接字。所以至少,必须维护一个对管理器的强引用以使套接字保持活动状态。

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.


[来自服务器的未知错误欢迎来到socket.io。]

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




  1. 在服务器端和客户端检查socket.io版本,两者不匹配可能是导致此错误的原因

  2. 在info.plist(字典类型)和子键允许任意负载(布尔类型)中添加应用传输安全设置键是值。

这篇关于Socket.io for swift4 ios的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆