为什么“打印到控制台”比“.text into label”

时间:2016-11-10 20:52:31

标签: ios console uilabel swift3

我正在尝试显示CMPedometer的节奏和速度数据。当我连接手机运行应用程序时,它会立即通过print("...")功能将数据输出写入控制台,但需要多次转动,直到它显示UILabel中的数据。 如何尽可能快地获取数据,以便我可以使用它们?

最好,扎克

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

1 个答案:

答案 0 :(得分:3)

在后台线程上调用更新块,您需要在主线程上更新UI。将调度中的UI更新调用包装回主线程:

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