I’m playing with starting to blog again.
This is the type of thing that I might enjoy posting.
I have a bunch of these, and this might be a good place to save them for posterity.
import HealthKit
static var healthStore: HKHealthStore = HKHealthStore()
var healthKitAuthorized = false
var dataTypesToWrite = Set<HKSampleType>()
var dataTypesToRead = Set<HKObjectType>()
func requestAccessToHealthKit(completion: ((Bool, Error?) -> Void)!) {
if HKHealthStore.isHealthDataAvailable() {
healthStore.requestAuthorization(toShare: dataTypesToWrite,
read: dataTypesToRead) { success, error in
if !success {
print(“Error: \(error!.localizedDescription.description)”)
} else {
healthKitAuthorized = true
}
if (completion != nil) {
completion(success, error)
}
}
} else {
print(“HealthKit is not available on this device.”)
}
}
func doStuff() {
dataTypesToWrite = Set([
HKObjectType.quantityType(forIdentifier:
HKQuantityTypeIdentifier.height)!,
HKObjectType.quantityType(forIdentifier:
HKQuantityTypeIdentifier.bodyMass)!
])
dataTypesToRead = Set([
HKObjectType.quantityType(forIdentifier:
HKQuantityTypeIdentifier.height)!,
HKObjectType.quantityType(forIdentifier:
HKQuantityTypeIdentifier.bodyMass)!
])
requestAccessToHealthKit { [weak self] (success, error) in
if success {
// Go ahead and work with HealthKit height and weight samples…
DispatchQueue.main.async {
// You’re in a background queue…
// …so if you’re going to work with the user interface…
// …be sure to wrap it in a dispatch to the main queue.
}
}
}
}
Customize the messages displayed on the permissions sheet by setting the following keys in your app’s info.plist file. Set the NSHealthShareUsageDescription
(Privacy – Health Share Usage Description) key to customize the message for reading data. Set the NSHealthUpdateUsageDescription
(Privacy – Health Update Usage Description) key to customize the message for writing data.