しめ鯖日記

swift, iPhoneアプリ開発, ruby on rails等のTipsや入門記事書いてます

HealthKitで身長の書き込み、読み込みをやってみる

HealthKitアプリを使ってデータの取得・保存を試してみました。

前準備

まずはプロジェクト設定のCapabilitiesをOnにします。

f:id:llcc:20160508124658p:plain

次にプロジェクト設定のGeneralのLinked Frameworks and LibrariesでHealthKit.frameworkを追加します。

f:id:llcc:20160508124755p:plain

ユーザーの許可を得る

requestAuthorizationToShareTypesメソッドでユーザーの許可を得ます。

let types = Set([
    HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight)!
])
let healthStore = HKHealthStore()
healthStore.requestAuthorizationToShareTypes(types, readTypes: types, completion: { success, error in
    print(success)
    print(error)
})

ユーザーにはこのような許可画面が表示されます。

f:id:llcc:20160508131453p:plain

データの保存

データの保存は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)
})

ヘルスケアアプリの方にもデータが反映されました。

f:id:llcc:20160508131705p:plain

データの取得

データの取得は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))