1

書式設定、理解不足、用語などについてお詫び申し上げます。まだ 2 日間しか学習していないので、あまり理解できていません。私は本業のグラフィック デザイナーで、データを必要とする個人用のアプリを作成しようとしており、視覚的に魅力的に見えるようにしています。1 日の歩数を作成し、この情報を健康アプリから取得したいと考えています。

まず、HealthKit の StepCount を呼び出して、その日の歩数を表示できるようになりました。ボタン (IBAction) を使用して stepCount データを取得し、テキスト文字列 (UILabel) に出力する限り、これは成功します。(たとえば、数値は小数点 66.0 で出力されますが、一度に 1 ステップずつ ha!)

今のところ、ボタンを押して操作するのではなく、「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