【发布时间】:2016-02-23 22:54:25
【问题描述】:
我试图简单地显示 Apple Watch 上次记录的心率。下面是我正在尝试的,但 updateHeartRate 的完成处理程序中的 results 变量会获取数百万条记录并杀死应用程序(几乎看起来像损坏的数据或做错了什么):
class InterfaceController: WKInterfaceController {
@IBOutlet var heartLabel: WKInterfaceLabel!
let heartRateUnit = HKUnit.countUnit().unitDividedByUnit(HKUnit.minuteUnit())
let heartRateQuantityType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
}
override func willActivate() {
super.willActivate()
guard HKHealthStore.isHealthDataAvailable() else {
heartLabel.setText("Not available")
return
}
requestHealthKitAuthorization()
queryHeartRateSample()
}
@IBAction func workoutMenuTapped() {
}
}
private extension InterfaceController {
func requestHealthKitAuthorization() {
guard let heartRateQuantityType = heartRateQuantityType else {
displayNotAllowed()
return
}
let dataTypes = Set(arrayLiteral: heartRateQuantityType)
HKHealthStore.sharedInstance?.requestAuthorizationToShareTypes(nil, readTypes: dataTypes) {
[unowned self] success, error in
guard success else {
self.displayNotAllowed()
return
}
self.queryHeartRateSample()
}
}
func displayNotAllowed() {
heartLabel.setText("Not allowed")
}
func queryHeartRateSample() {
guard let heartRateQuery = getHeartRateQuery() else { return }
HKHealthStore.sharedInstance?.executeQuery(heartRateQuery)
}
func updateHeartRate(samples: [HKSample]?) {
guard let heartRateSamples = samples as? [HKQuantitySample] else { return }
dispatch_async(dispatch_get_main_queue()) {
guard let sample = heartRateSamples.first else { return }
let value = sample.quantity.doubleValueForUnit(self.heartRateUnit)
self.heartLabel.setText(String(UInt16(value)))
}
}
func getHeartRateQuery() -> HKQuery? {
guard let heartRateQuantityType = heartRateQuantityType else {
displayNotAllowed()
return nil
}
let heartRateQuery = HKSampleQuery(sampleType: heartRateQuantityType,
predicate: nil,
limit: 100,
sortDescriptors: nil) {
[unowned self] query, results, error in
guard let results = results as? [HKQuantitySample] else { return }
self.updateHeartRate(results)
}
return heartRateQuery
}
}
@available(iOS 8.0, *)
public extension HKHealthStore {
class var sharedInstance: HKHealthStore? {
if !HKHealthStore.isHealthDataAvailable() {
return nil
}
struct Singleton {
static let instance = HKHealthStore()
}
return Singleton.instance
}
}
它确实要求我授予权限,但仍然不会触发更新。我是不是做错了什么?
【问题讨论】:
标签: swift swift2 watchkit apple-watch healthkit