问题
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