gpt4 book ai didi

ios - 函数返回值为空 : Why?

转载 作者:行者123 更新时间:2023-11-30 10:52:33 29 4
gpt4 key购买 nike

在 QueryHK 类中,我运行 HealthKit 查询以获取步骤和相应的日期。我想将这些数据写入 NSArray 并返回它,以便我可以调用 ViewController 中的函数。

  • 问题: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)

}
}

最佳答案

原因是 HKSampleQuery 是异步处理的 - 它立即返回并在后台工作。因此,您的方法立即完成执行,而不是在结果处理程序 block 中处理响应。您需要更新您的方法以采用完成 block 而不是返回值。

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)
}
}
}

关于ios - 函数返回值为空 : Why?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54307325/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com