iosswiftmultithreadinguilabelcbperipheral

Swift - How to update UILabel from a function


i'm making a bluetooth app and i want to put 2 labels to control if i'm connected and to display the RSSI so i have write this function

func updateLabel(){
    LRSSI.text = String(RSSINb)
    if(Connected == true){
        LEtat.text = "Connected"
        LEtat.textColor = UIColor.green
    }else{
        LEtat.text = "Disconnected"
        LEtat.textColor = UIColor.red
    }
}


I call this function inside my ReadRSSI function from CBPeripheral.
There is this text in my terminal

Main Thread Checker: UI API called on a background thread: -[UILabel setText:]

But when i rotate my phone it update labels, i tried to put 'self' before my labels.
I also tried to call my function inside a timer but it gives me a SIGBART error
So is there a method to update labels or to reload viewcontroller ?

EDIT : Call of my function:

 func peripheral(_ peripheral: CBPeripheral, didReadRSSI RSSI: NSNumber, error: Error?) {
    print(RSSI)
    peripheral.readRSSI()

    RSSINb = Int(RSSI) * -1
    updateLabel()
    if(RSSINb > 150){
        WriteValue(valeur: "z")
    }
}

EDIT :

What's the proper way in architecture design to avoid UI API to be called on a background thread?


Solution

  • Problem Solved:

    func peripheral(_ peripheral: CBPeripheral, didReadRSSI RSSI: NSNumber, error: Error?) {
        print(RSSI)
        peripheral.readRSSI()
    
        RSSINb = Int(RSSI) * -1
        DispatchQueue.main.sync {
            updateLabel()
        }
        if(RSSINb > 150){
            WriteValue(valeur: "z")
        }
    }