How change label text with received data via UDP using CocoaAsyncSocket

女生的网名这么多〃 提交于 2019-12-13 04:07:15

问题


I am using CocoaAsyncSocket to send and receive data from ESP32 device via UDP. I can send data(String) without problem, even can receive data and print it with print("incoming message: \(data)") But I can not change label text with this data.

I have label @IBOutlet weak var mylabel1: UILabel? in class ViewController: UIViewController, then I have inSocket and OutSocket class in separate swift file.

But when I receive data with inSocket class(in separate swift file), I can just print it with print() but not change text of label defined in separate ViewController swift file.

ViewController.swift file:

class ViewController: UIViewController {
    var inSocket : InSocket!
    var outSocket : OutSocket!

    @IBOutlet weak var mylabel1: UILabel?
    @IBOutlet weak var btn_minus1: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        inSocket = InSocket()
        outSocket = OutSocket()
        outSocket.setupConnection {

        }

        //mylabel1.text = change_label
        //mylabel1?.text = "22"
    }

    func updateLabel(l_value: String?) {
        print("Contains a value! It is \(String(describing: l_value))!")

        if let label = mylabel1
        {
            label.text = l_value
            print("label changed")
            //mylabel1?.text = "22"
        }else{
            print("label not changed")
        }
...

InSocket.swift file:

       class InSocket: NSObject, GCDAsyncUdpSocketDelegate {

        //let IP = "192.168.5.122"
        let IP = "192.168.5.143"
        let PORT:UInt16 = 8690
        var socket:GCDAsyncUdpSocket!

        var controller = ViewController()
        //var ViewController:ViewController?
        //var change_label = "--";
        //var text:String = ""

        //@IBOutlet weak var mylabel1: UILabel?

        override init(){
            super.init()
            setupConnection()

        }

        func udpSocket(_ sock: GCDAsyncUdpSocket, didReceive data: Data, fromAddress address: Data, withFilterContext filterContext: Any?) {
            print("incoming message: \(data)");

                    controller.updateLabel(l_value: String(data: data, encoding: .utf8) ?? "null")

...

来源:https://stackoverflow.com/questions/56203943/how-change-label-text-with-received-data-via-udp-using-cocoaasyncsocket

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!