我知道這個問題已被問到,但並沒有真正回答。我試過這樣的線程的東西: Heart Rate With Apple's Healthkit如何閱讀healthKit心率數據?
我試圖將此從Objective-C轉換爲Swift,但沒有奏效。
我的問題是,從健康套件中讀取心率數據的最佳方式是什麼?我希望能夠讀取每次心率測量的時間,並且希望能夠看到所述測量的時間/日期戳。
我要求准許在這裏:
import Foundation
import UIKit
import HealthKit
class HealthKitManager: NSObject {
static let healthKitStore = HKHealthStore()
static func authorizeHealthKit() {
let healthKitTypes: Set = [
HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)!,
]
healthKitStore.requestAuthorizationToShareTypes(healthKitTypes,
readTypes: healthKitTypes) { _, _ in }
}
}
這裏是我的視圖控制器代碼現在(我不知道爲什麼這不工作):
import UIKit
import HealthKit
class ViewController: UIViewController {
let health: HKHealthStore = HKHealthStore()
let heartRateUnit:HKUnit = HKUnit(fromString: "count/min")
let heartRateType:HKQuantityType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)!
var heartRateQuery:HKQuery?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func authorizeTapped(sender: AnyObject) {
print("button tapped")
self.createStreamingQuery()
HealthKitManager.authorizeHealthKit()
}
func createStreamingQuery() -> HKQuery
{
let queryPredicate = HKQuery.predicateForSamplesWithStartDate(NSDate(), endDate: nil, options: .None)
let query:HKAnchoredObjectQuery = HKAnchoredObjectQuery(type: self.heartRateType, predicate: queryPredicate, anchor: nil, limit: Int(HKObjectQueryNoLimit))
{ (query:HKAnchoredObjectQuery, samples:[HKSample]?, deletedObjects:[HKDeletedObject]?, anchor:HKQueryAnchor?, error:NSError?) -> Void in
if let errorFound:NSError = error
{
print("query error: \(errorFound.localizedDescription)")
}
else
{
//printing heart rate
if let samples = samples as? [HKQuantitySample]
{
if let quantity = samples.last?.quantity
{
print("\(quantity.doubleValueForUnit(self.heartRateUnit))")
}
}
}
}
query.updateHandler =
{ (query:HKAnchoredObjectQuery, samples:[HKSample]?, deletedObjects:[HKDeletedObject]?, anchor:HKQueryAnchor?, error:NSError?) -> Void in
if let errorFound:NSError = error
{
print("query-handler error : \(errorFound.localizedDescription)")
}
else
{
//printing heart rate
if let samples = samples as? [HKQuantitySample]
{
if let quantity = samples.last?.quantity
{
print("\(quantity.doubleValueForUnit(self.heartRateUnit))")
}
}
}//eo-non_error
}//eo-query-handler
return query
}
}
我不能得到任何東西打印到控制檯,這真的只是我想要的。
此外,這些代碼都不會涉及作業,個人/專業項目等。它只是爲了好玩/學習,而且大部分代碼都是我嘗試的,以及我通過多種堆棧和其他論壇發現的內容。
你有沒有真的執行'createStreamingQuery'函數? – jtbandes
我做了,並沒有打印到控制檯,不知道爲什麼。 – dnaland
您是否在健康商店使用executeQuery? – jtbandes