###前提・実現したいこと
xcode8.1 swift3
現在私は一定時間の平均の心拍数を受け取るプログラムを考えております。
そのアルゴリズムは
applewatchのデフォルトのアプリで心拍数を取得し、ヘルスケアに保存。
ヘルスケアに保存された心拍数のデータの平均値をiPhoneが取得するというものです。
心拍数のデータの平均値をiPhoneが取得するところで、まずテストとして
自分はこちらが用意したデータをヘルスケアに保存させてから、
取得を行おうとしました。
###発生している問題・エラーメッセージ
その最中にエラーは起きないのですが、 読み込む値にnilが入ってしまいます。
###該当のソースコード
/* 保存するデータの準備 */ // 心拍数 let heatRate = "60" // 心拍数の単位 let unit2 = HKUnit(from: "count/min") // 心拍数情報のタイプ let type2 = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate)! // healthKitデータ保存領域のインスタンス化 let healthStore = HKHealthStore() let helthData2 = HKQuantity(unit: unit2, doubleValue: Double(heatRate)!) // 時間設定 let now: NSDate = NSDate() let calendar = Calendar(identifier: .gregorian) let inAfterMintes = calendar.date(byAdding: .minute, value: 30, to: now as Date) let sample2 = HKQuantitySample(type: type2, quantity: helthData2, start: now as Date, end: inAfterMintes) let authorizedStatus2 = healthStore.authorizationStatus(for: type2) // HealthKitデータ保存領域へのアクセス権限があればデータ保存。なければ、アクセス権限の確認画面へ移動 if authorizedStatus2 == .sharingAuthorized{ healthStore.save(sample2, withCompletion: { (success, error) in if error != nil { // NSLog(error!.description); return } if success { healthStore.save(sample2, withCompletion:{ (success, error) in print("保存成功") }) } }) }else{ healthStore.requestAuthorization(toShare: [type2], read: [type2], completion: { (success, error) in if error != nil { // NSLog(error!.description); return } // アクセス権限を得たらデータを保存 if success { healthStore.save(sample2, withCompletion:{ (success, error) in print("保存成功") }) } }) } } /// HealthStoreから心拍数データを取得します。 // データの種類 let type2 = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.heartRate)! // データ取得 let healthStore = HKHealthStore() // 日付処理 let now: NSDate = NSDate() let calendar = Calendar(identifier: .gregorian) let inAfterMintes = calendar.date(byAdding: .minute, value: 30, to: now as Date)! let predicate: NSPredicate = HKQuery.predicateForSamples(withStart: now as Date, end: inAfterMintes, options: HKQueryOptions.strictStartDate) let startOptions: HKStatisticsOptions = HKStatisticsOptions.discreteAverage // データ抽出クエリ let query: HKStatisticsQuery = HKStatisticsQuery(quantityType: type2, quantitySamplePredicate: predicate, options: startOptions, completionHandler: { (query, result, error) in DispatchQueue.global().async { print("my heartrate is \(result!.averageQuantity())") } }) healthStore.execute(query)
###試したこと
保存した時間帯と読み込む時間帯を一緒にした
###補足情報
下から5行目のprint文で
"my heartrate is nil" と表示される
回答1件
あなたの回答
tips
プレビュー