如何使用CocoaAsyncSocket通过UDP更改带有接收数据的标签文本

时间:2019-05-19 00:53:24

标签: swift cocoa cocoaasyncsocket

我正在使用CocoaAsyncSocket通过UDP从ESP32设备发送和接收数据。我可以毫无问题地发送数据(字符串),甚至可以接收数据并使用print("incoming message: \(data)")打印 但是我无法使用此数据更改标签文本。

我在@IBOutlet weak var mylabel1: UILabel?中有标签class ViewController: UIViewController,然后在单独的swift文件中有inSocket和OutSocket类。

但是当我使用inSocket类(在单独的swift文件中)接收数据时, 我只能使用print()打印它,而不能更改在单独的ViewController swift文件中定义的标签文本。

ViewController.swift文件:

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文件:

       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")

...

0 个答案:

没有答案