在QueryHK类中,我为步骤和相应的日期运行HealthKit查询。我想将这些数据写入NSArray并返回它,以便我可以在ViewController中调用该函数。
在我看来,查询不会“写入返回”。
QueryHK.swift:
import UIKit
import HealthKit
class QueryHK: NSObject {
var steps = Double()
var date = NSDate()
func performHKQuery () -> (steps: Double, date: NSDate){
let healthKitManager = HealthKitManager.sharedInstance
let stepsSample = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)
let stepsUnit = HKUnit.countUnit()
let sampleQuery = HKSampleQuery(
sampleType: stepsSample,
predicate: nil,
limit: 0,
sortDescriptors: nil)
{
(sampleQuery, samples, error) in
for sample in samples as [HKQuantitySample]
{
self.steps = sample.quantity.doubleValueForUnit(stepsUnit)
self.date = sample.startDate
println("Query HealthKit steps: \(self.steps)")
println("Query HealthKit date: \(self.date)")
}
}
healthKitManager.healthStore.executeQuery(sampleQuery)
return (steps, date)
}
}
ViewController.swift:
import UIKit
class ViewController: UIViewController {
var query = QueryHK()
override func viewDidLoad() {
super.viewDidLoad()
printStepsAndDate()
}
func printStepsAndDate() {
println(query.performHKQuery().date)
println(query.performHKQuery().steps)
}
}
答案 0 :(得分:1)
原因是HKSampleQuery
是异步处理的 - 它会立即返回并在后台运行。因此,您的方法立即完成执行,而不是在结果处理程序块中处理响应。您需要更新方法以获取完成块而不是返回值。
<强> QueryHK.swift:强>
import UIKit
import HealthKit
struct Sample {
let step: Double
let date: NSDate
}
class QueryHK: NSObject {
func performHKQuery(completion: (samples: [Sample]) -> Void) {
let healthKitManager = HealthKitManager.sharedInstance
let stepsSample = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)
let stepsUnit = HKUnit.countUnit()
let sampleQuery = HKSampleQuery(
sampleType: stepsSample,
predicate: nil,
limit: 0,
sortDescriptors: nil)
{
(sampleQuery, samples, error) in
var processedSamples = [Sample]()
for sample in samples as [HKQuantitySample]
{
processedSamples.append(Sample(step: sample.quantity.doubleValueForUnit(stepsUnit), date: sample.startDate))
println("Query HealthKit steps: \(processedSamples.last?.step)")
println("Query HealthKit date: \(processedSamples.last?.date)")
}
// Call the completion handler with the results here
completion(samples: processedSamples)
}
healthKitManager.healthStore.executeQuery(sampleQuery)
}
}
<强> ViewController.swift:强>
import UIKit
class ViewController: UIViewController {
var query = QueryHK()
override func viewDidLoad() {
super.viewDidLoad()
printStepsAndDate()
}
func printStepsAndDate() {
query.performHKQuery() { steps in
println(steps)
}
}
}