Healthkit没有返回iphone的最新数据。在iPhone和Apple手表之间使用healthkit

时间:2018-01-24 18:48:43

标签: ios iphone swift apple-watch health-kit

我正在创建一个提供锻炼信息的应用。在苹果手表上,我有三个标签,主动显示HEARTRATE,DISTANCE TRAVELED和CALORIES BURNED。苹果手表的情况很好,但事情变坏的地方是我试图在iphone上实时显示这些数据。

APPLE WATCH PART: -

我开始在苹果手表上锻炼并使用下载代码保存它

 func startWorkoutSession() {
    // Start a workout session with the configuration
    if let workoutConfiguration = configuration {
        do {
            workoutSession = try HKWorkoutSession(configuration: workoutConfiguration)
            workoutSession?.delegate = self
            workoutStartDate = Date()

            healthStore.start(workoutSession!)

        } catch {
            // ...
        }
    }
}

然后我使用以下代码在Apple Watch上保存该锻炼: -

 func saveWorkout() {
    // Create and save a workout sample
    let configuration = workoutSession!.workoutConfiguration
    let isIndoor = (configuration.locationType == .indoor) as NSNumber
    print("locationType: \(configuration)")

    let workout = HKWorkout(activityType: configuration.activityType,
                            start: workoutStartDate ?? Date(),
                            end: workoutEndDate ?? Date(),
                            workoutEvents: workoutEvents,
                            totalEnergyBurned: totalEnergyBurned,
                            totalDistance: totalDistance,
                            metadata: [HKMetadataKeyIndoorWorkout:isIndoor]);

    healthStore.save(workout) { success, _ in
        if success {
            self.addSamples(toWorkout: workout)
        }
    }

    // Pass the workout to Summary Interface Controller
    // WKInterfaceController.reloadRootControllers(withNames: ["StopPauseInterfaceController"], contexts: [workout])


    if #available(watchOSApplicationExtension 4.0, *){
        // Create the route, save it, and associate it with the provided workout.
        routeBuilder?.finishRoute(with: workout, metadata: metadata) { (newRoute, error) in

            guard newRoute != nil else {
                // Handle the error here...
                return
            }
        }
    }
    else {
        // fallback to earlier versions
    }
}

然后我使用以下代码将样本添加到这些训练中: -

 func addSamples(toWorkout workout: HKWorkout) {
    // Create energy and distance samples
    let totalEnergyBurnedSample = HKQuantitySample(type: HKQuantityType.activeEnergyBurned(),
                                                   quantity: totalEnergyBurned,
                                                   start: workoutStartDate!,
                                                   end: workoutEndDate ?? Date())

    let totalDistanceSample = HKQuantitySample(type: HKQuantityType.distanceWalkingRunning(),
                                               quantity: totalDistance,
                                               start: workoutStartDate!,
                                               end: workoutEndDate ?? Date())

    // Add samples to workout
    healthStore.add([totalEnergyBurnedSample, totalDistanceSample], to: workout) { (success: Bool, error: Error?) in
        if success {
            // Samples have been added
        }
    }
}

IPHONE PART: -

这是事情变得更糟的地方。我尝试使用HKSampleObjectQuery访问healthkit存储,它只返回静态值。 P.S - 我每隔一秒钟使用NSTimer获取最新数据的healthkit商店。

每秒调用的代码是: -

func extractDataFromHealthStore(identifier : HKQuantityTypeIdentifier,completion: @escaping (String) -> ()) {


    let heightType = HKSampleType.quantityType(forIdentifier:identifier)!
    let distantPastDate = Date.distantPast
    let endDate = Date()

    let predicate = HKQuery.predicateForSamples(withStart: distantPastDate, end: endDate, options: .strictStartDate)

    // Get the single most recent Value
    let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: true)


    let query = HKSampleQuery(sampleType: heightType, predicate: predicate, limit: 1, sortDescriptors: [sortDescriptor]) { (query, results, error) in
        if let result = results?.first as? HKQuantitySample{
            print("Height => \(result.quantity)")

            completion("\(result.quantity)")

        }else{
            print("OOPS didnt get height \nResults => \(String(describing: results)), error => \(error)")
             completion("")
        }
    }
    self.healthStore.execute(query)
}

如果我的整个方法错了,请指导我,或者如果它是对的,那么我的错误是什么。

0 个答案:

没有答案