HealthKitアプリを使ってデータの取得・保存を試してみました。
前準備
まずはプロジェクト設定のCapabilitiesをOnにします。
次にプロジェクト設定のGeneralのLinked Frameworks and LibrariesでHealthKit.frameworkを追加します。
ユーザーの許可を得る
requestAuthorizationToShareTypesメソッドでユーザーの許可を得ます。
let types = Set([ HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight)! ]) let healthStore = HKHealthStore() healthStore.requestAuthorizationToShareTypes(types, readTypes: types, completion: { success, error in print(success) print(error) })
ユーザーにはこのような許可画面が表示されます。
データの保存
データの保存はsaveObjectメソッドを使います。
let healthStore = HKHealthStore() let quantity = HKQuantity(unit: HKUnit.meterUnit(), doubleValue: 180) let height = HKQuantitySample(type: type!, quantity: quantity, startDate: NSDate(), endDate: NSDate()) healthStore.saveObject(height, withCompletion: { success, error in print(success) print(error) })
ヘルスケアアプリの方にもデータが反映されました。
データの取得
データの取得はexecuteQueryメソッドで行います。
let healthStore = HKHealthStore() let type = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight) let query = HKSampleQuery(sampleType: type!, predicate: nil, limit: 10, sortDescriptors: nil, resultsHandler: { query, data, error in print(query) print(data) // → Optional([180 m "MyApp" (1) 2016-05-08 13:16:51 +0900 2016-05-08 13:16:51 +0900]) print(error) }) print(healthStore.executeQuery(query))