Zack Peng Zack Peng - 25 days ago 5
iOS Question

Why is "print into console" much faster than ".text into label "

I´m trying to display the cadence and pace data of

CMPedometer
. When I run the application with my phone attached, it writes the output of the data immediately through the
print("...")
function into the console, but takes multiple turns until it displays the data in the
UILabel
.
How can I get the data as fast as possible so I can use them?

Best, Zack

import UIKit
import CoreMotion

class ViewController: UIViewController {
let pedometer = CMPedometer()
@IBOutlet weak var paceLabel: UILabel!
@IBOutlet weak var cadenceLabel: UILabel!

override func viewDidLoad() {
super.viewDidLoad()

guard CMPedometer.isCadenceAvailable() && CMPedometer.isPaceAvailable() else{
print("Pace and cadence data are not available")
return
}
let oneWeekAgo = NSDate(timeIntervalSinceNow: -(7 * 24 * 60 * 60))
pedometer.startUpdates(from: oneWeekAgo as Date) {data, error in
guard let pData = data , error == nil else{
return
}
//The current pace of the user, measured in seconds per meter. (1 step = 83cm?)
if let pace = pData.currentPace{
print("Pace = \(pace)")
self.paceLabel.text = "Pace = \(round(Double(pace))*10/10)"
}
//The rate at which steps are taken, measured in steps per second.
if let cadence = pData.currentCadence{
self.cadenceLabel.text = "Cadence = \(cadence))"
print("Cadence = \(cadence)")
}
}// -----------------oneWeekAgo
}// -----------------ViewDidLoad

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}//-------------------- UIViewController

dan dan
Answer

The update block is called on a background thread and you need to update your UI on the main thread. Wrap the UI update calls in a dispatch back to the main thread:

Dispatch.main.async {
    //The current pace of the user, measured in seconds per meter. (1 step = 83cm?)
    if let pace = pData.currentPace{
        print("Pace = \(pace)")
        self.paceLabel.text = "Pace = \(round(Double(pace))*10/10)"
    }

    //The rate at which steps are taken, measured in steps per second.
    if let cadence = pData.currentCadence{
        self.cadenceLabel.text = "Cadence = \(cadence))"
            print("Cadence = \(cadence)")
        }
    }
}
Comments