1

为我的格式,缺乏理解,术语等道歉。我才学习了两天,所以我还是不太明白。我是一名平面设计师,我正在尝试制作一个个人使用的应用程序,它需要一些数据,并让它在视觉上对我更有吸引力。我想创建一天的步数并从健康应用程序中提取此信息。

首先,我已经达到了可以调用 HealthKit StepCount 来显示当天所采取的步骤的程度。只要我使用按钮(IBAction)来获取stepCount数据,然后输出到文本字符串(UILabel),这就是成功的。(例如输出带小数点 66.0 的数字,但一次一步哈!)

现在,我想简单地自动填充“totalSteps UILabel”以显示 stepCount,而不是通过按下按钮来操作它。

我尝试了很多不同的方法,我忘记了我尝试过的内容以及尝试的代码放在哪里,所以任何帮助和/或简短的解释都会很棒!

谢谢你

import UIKit
import HealthKit

class ViewController: UIViewController {

    @IBOutlet weak var totalSteps: UILabel!
    @IBOutlet weak var quotePhrase: UITextView!

    let healthStore = HKHealthStore()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.


        func authoriseHealthKitAccess(_ sender: Any) {
            let healthKitTypes: Set = [
                // access step count
                HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!
            ]
            healthStore.requestAuthorization(toShare: healthKitTypes, read: healthKitTypes) { (_, _) in
                print("authrised???")
            }
            healthStore.requestAuthorization(toShare: healthKitTypes, read: healthKitTypes) { (bool, error) in
                if let e = error {
                    print("oops something went wrong during authorisation \(e.localizedDescription)")
                } else {
                    print("User has completed the authorization flow")
                }
            }
        }  
    }

    func getTodaysSteps(completion: @escaping (Double) -> Void) {

        let stepsQuantityType = HKQuantityType.quantityType(forIdentifier: .stepCount)!

        let now = Date()
        let startOfDay = Calendar.current.startOfDay(for: now)
        let predicate = HKQuery.predicateForSamples(withStart: startOfDay, end: now, options: .strictStartDate)

        let query = HKStatisticsQuery(quantityType: stepsQuantityType, quantitySamplePredicate: predicate, options: .cumulativeSum) { (_, result, error) in
            var resultCount = 0.0
            guard let result = result else {
                print("Failed to fetch steps rate")
                completion(resultCount)
                return
            }
            if let sum = result.sumQuantity() {
                resultCount = sum.doubleValue(for: HKUnit.count())
            }

            DispatchQueue.main.async {
                completion(resultCount)
            }
        }
        healthStore.execute(query)
    }

    //Button Action Here:

    @IBAction func getTotalSteps(_ sender: Any) {
        getTodaysSteps { (result) in
            print("\(result)")
            DispatchQueue.main.async {
                self.totalSteps.text = "\(result)"
            }
        }
    }
}
4

1 回答 1

0

您只需要在viewDidLoad. 当用户授予访问健康数据的权限时,您还应该调用该代码。我在下面的代码中介绍了这两种情况。

import UIKit
import HealthKit

class ViewController: UIViewController {

    @IBOutlet weak var totalSteps: UILabel!
    @IBOutlet weak var quotePhrase: UITextView!

    let healthStore = HKHealthStore()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.authoriseHealthKitAccess()
    }

    func authoriseHealthKitAccess() {
            let healthKitTypes: Set = [
                // access step count
                HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!
            ]
            healthStore.requestAuthorization(toShare: healthKitTypes, read: healthKitTypes) { [weak self] (bool, error) in
                if let e = error {
                    print("oops something went wrong during authorisation \(e.localizedDescription)")
                } else {
                    print("User has completed the authorization flow")
                    self?.updateStepsCountLabel()
                }
           }
     }

    func getTodaysSteps(completion: @escaping (Double) -> Void) {

        let stepsQuantityType = HKQuantityType.quantityType(forIdentifier: .stepCount)!

        let now = Date()
        let startOfDay = Calendar.current.startOfDay(for: now)
        let predicate = HKQuery.predicateForSamples(withStart: startOfDay, end: now, options: .strictStartDate)

        let query = HKStatisticsQuery(quantityType: stepsQuantityType, quantitySamplePredicate: predicate, options: .cumulativeSum) { (_, result, error) in
            var resultCount = 0.0
            guard let result = result else {
                print("Failed to fetch steps rate")
                completion(resultCount)
                return
            }
            if let sum = result.sumQuantity() {
                resultCount = sum.doubleValue(for: HKUnit.count())
            }

            DispatchQueue.main.async {
                completion(resultCount)
            }
        }
        healthStore.execute(query)
    }

    private func updateStepsCountLabel() {
        getTodaysSteps { (result) in
            print("\(result)")
            DispatchQueue.main.async {
                self.totalSteps.text = "\(result)"
            }
        }
    }

    //Button Action Here:

    @IBAction func getTotalSteps(_ sender: Any) {
        updateStepsCountLabel()
    }
}
于 2018-10-09T04:52:25.463 回答