TransWikia.com

Main Thread Checker Error: Double to UILabel Fails Swift

Stack Overflow Asked by Nisse82 on December 13, 2021

I am collecting some data from an API that Im then running some calculations on. The numbers are stored as Doubles since i want the decimals. Calculations and all running smooth, getting correct printouts in the console, however I cannot seem to get it to update my UILabel. Im getting the following error in the console (it builds successfully btw):

Main Thread Checker: UI API called on a background thread: -[UILabel setText:]
PID: 69869, TID: 13575919, Thread name: (none), Queue name: NSOperationQueue 0x113e13690 (QOS: UNSPECIFIED), QoS: 0

Here is my code and my calculations. The values are updated through the API so they’re not just 0 when I do the calculations:

    @IBOutlet weak var renewableLabel: UILabel!
    
    var hydroValue : Double = 0
    var windValue : Double = 0
    
    var renewables : Double = 0
    var renewPercent : Double = 0

 func calcIndex(){
        
        renewables = windValue + hydroValue
        renewPercent = Double(round(10*((renewables / productionValue) * 100))/10)
        
        //print(productionValue)
        
        print("(renewPercent) %")
           
        updateLabel()
}

func updateLabel(){
        renewableLabel.text = ("(renewPercent)")
    }

I tried reformatting the Double as a String prior to sending it to the Label but still the samr error. If I do this above in a different project with just the Doubles the renewableLabel.text = ("(renewPercent)") works fine. Im not sure even if a UILable is the best choice here. Im happy to switch :).

One Answer

The issue has nothing to do with your calculations or numeric types you use.

You need to dispatch your UI update to the main thread as the error clearly says.

func updateLabel(){
    DispatchQueue.main.async {
        self.renewableLabel.text = ("(self.renewPercent)")
    }
}

Answered by Dávid Pásztor on December 13, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP