Swift - 练习时间Healthkit

时间:2018-03-27 16:49:54

标签: ios swift health-kit

所以我一直试图将Healthkit的练习时间记录到我的应用程序中并将其存储在变量中。

但是每当应用程序在连接到苹果wathc的Iphone上打开时,它就会崩溃。我已经尝试调试应用程序,但它在模拟器或我的Ipod触摸上工作正常。这是我用来检索锻炼时间的功能。

func getExerciseTime(completion: @escaping (Double) -> Void) {
    let exerciseQuantityType = HKQuantityType.quantityType(forIdentifier: .appleExerciseTime)!

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

    var now : Date
    var startOfDay : Date
    var predicate : NSPredicate

    switch dwmValue {
    case 0:
        now = Date()
        startOfDay = Calendar.current.startOfDay(for: now)
        predicate = HKQuery.predicateForSamples(withStart: startOfDay, end: now, options: .strictStartDate)
        break
    case 1:
        now = Date()
        startOfDay = Calendar.current.startOfDay(for: Date(timeIntervalSinceNow: -60 * 60 * 24 * 7))
        predicate = HKQuery.predicateForSamples(withStart: startOfDay, end: now, options: .strictStartDate)
        break
    case 2:
        now = Date()
        let wx = -60 * 60 * 24 * 2
        startOfDay = Calendar.current.startOfDay(for: Date(timeIntervalSinceNow: TimeInterval((-60 * 60 * 24 * 7 * 4) + wx)))
        predicate = HKQuery.predicateForSamples(withStart: startOfDay, end: now, options: .strictStartDate)
        break
    default:
        now = Date()
        startOfDay = Calendar.current.startOfDay(for: now)
        predicate = HKQuery.predicateForSamples(withStart: startOfDay, end: now, options: .strictStartDate)
        break
    }

    let query = HKStatisticsQuery(quantityType: exerciseQuantityType, quantitySamplePredicate: predicate, options: .cumulativeSum ) { (_, result, error) in
        var resultCount = 0.0



        guard let result = result else {
            //log.error("Failed to fetch steps = \(error?.localizedDescription ?? "N/A")")
            completion(resultCount)

            return
        }

        if let sum = result.sumQuantity() {
            resultCount = sum.doubleValue(for: HKUnit.count())


        }

        DispatchQueue.main.async {
            completion(resultCount)
            print("Exercise time : \(resultCount)")

        }
    }

    healthKitStore.execute(query)


}

这是我在viewdidAppear中使用的代码,用于将上述函数的值存储在全局变量中

 getExerciseTime(){ time in

                exerciseTime = time
            }

我不知道为什么应用程序不断崩溃在Iphone上。我试图改变StatisticsQuery中的选项但没有任何效果。请帮帮我!!我知道healthkit身份验证没有问题,因为它会在模拟器和iPod上返回一些数据,但会在连接到Apple Watch的Iphone上崩溃。

1 个答案:

答案 0 :(得分:0)

当您汇总数量时,您使用的是不兼容的类型(HKUnit.count()),您需要使用时间单位。

resultCount = sum.doubleValue(for: HKUnit.minute())

此外,如果您还没有这样做,则需要请求阅读许可

override func viewDidAppear(_ animated: Bool) {
    healthKitStore.requestAuthorization(toShare: nil, read: [exerciseQuantityType], completion: { (userWasShownPermissionView, error) in
        self.getExerciseTime(){ time in

            self.exerciseTime = time
        }
    })
}

您需要在plist中设置使用说明

<key>NSHealthShareUsageDescription</key>
<string>Foo</string>

您的应用程序需要在项目目标设置中设置HealthKit功能。

相关问题