HealthKit函数调用后Swift 2D数组为空-线程问题

时间:2019-06-26 19:39:46

标签: ios swift health-kit

我正在用HealthKit数据填充二维数组。只要该功能在30天之内循环,它就可以正常工作。在该函数之外,该数组为空,因为HealthKit数据已在后台加载,并且其他所有内容之前都已执行。

如何等待数据加载完毕才能访问数组中的数据?

这是我的ViewController内发生的事情

            print("function call starting") // 1
        // Populate 2DArrays
        self.hkManager.getTotalCalories(forDay: 30) {caloriesValue, date   in
            //check if caloriesValue is nil, only do something if it's not
            guard let caloriesValue = caloriesValue else { return }
            let dateValue = DateFormatter.localizedString(from: date!, dateStyle: .short, timeStyle: .none)
            print("will append") // 7 (31x)
            self.caloriesArray.append([(dateValue,caloriesValue)])
    }

        print("function call done") // 2
        print(self.caloriesArray.count) // 3

        hkManager.getWeightData(forDay: 30) {bodyMassValue, date   in
            // Check if bodyMassValue is nil, only do something, if it's not
            guard let bodyMassValue = bodyMassValue else { return }
            let dateValue = DateFormatter.localizedString(from: date!, dateStyle: .short, timeStyle: .none)
            self.bodyMassArray.append([(dateValue,bodyMassValue)])
        }

        do {
            self.age = try hkManager.getAge()
        } catch let error {
            print("Error calculating age: \(error)")
        }

        print(bodyMassArray) // 4
        print(caloriesArray) // 5
        print(age!) // 6
}

我在print语句后面添加了数字,以明确何时执行操作。

我正在调用的函数如下:

    func getTotalCalories(forDay days: Int, completion: @escaping ((_ calories: Int?, _ date: Date?) -> Void)) {
    // Getting quantityType as .dietaryCaloriesConsumed
    guard let calories = HKObjectType.quantityType(forIdentifier: .dietaryEnergyConsumed) else {
        print("*** Unable to create a dietaryEnergyConsumed type ***")
        return
    }

    let now = Date()
    let startDate = Calendar.current.date(byAdding: DateComponents(day: -days), to: now)!
    var interval = DateComponents()
    interval.day = 1

    var anchorComponents = Calendar.current.dateComponents([.day, .month, .year], from: now)
    anchorComponents.hour = 0
    let anchorDate = Calendar.current.date(from: anchorComponents)!

    let query = HKStatisticsCollectionQuery(quantityType: calories,
                                            quantitySamplePredicate: nil,
                                            options: [.cumulativeSum],
                                            anchorDate: anchorDate,
                                            intervalComponents: interval)
    query.initialResultsHandler = { _, results, error in
        guard let results = results else {
            print("ERROR")
            return
        }

        results.enumerateStatistics(from: startDate, to: now) { statistics, _ in
            DispatchQueue.main.async {
                if let sum = statistics.sumQuantity() {
                    let calories = Int(sum.doubleValue(for: HKUnit.kilocalorie()).rounded())
                    completion(calories, statistics.startDate)
                    return
                }
            }
        }
    }
    healthStore.execute(query)
}

有人知道我需要做什么吗? 谢谢! :)

0 个答案:

没有答案