Skip to content

Instantly share code, notes, and snippets.

@nderkach
Last active September 14, 2018 17:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nderkach/644a24d8b0b059ec97eee9907dcdfa89 to your computer and use it in GitHub Desktop.
Save nderkach/644a24d8b0b059ec97eee9907dcdfa89 to your computer and use it in GitHub Desktop.
private let healthStore = HKHealthStore()
/// Requests access to all the data types the app wishes to read/write from HealthKit.
/// On success, data is queried immediately and observer queries are set up for background
/// delivery. This is safe to call repeatedly and should be called at least once per launch.
func requestAccessWithCompletion(completion: @escaping AccessRequestCallback) {
guard HKHealthStore.isHealthDataAvailable() else {
debugPrint("Can't request access to HealthKit when it's not supported on the device.")
return
}
let writeDataTypes = dataTypesToWrite()
let readDataTypes = dataTypesToRead()
healthStore.requestAuthorization(toShare: writeDataTypes, read: readDataTypes) { [weak self] (success: Bool, error: Error?) in
guard let strongSelf = self else { return }
if success {
debugPrint("Access to HealthKit data has been granted")
strongSelf.setUpBackgroundDeliveryForDataTypes(types: readDataTypes)
} else {
debugPrint("Error requesting HealthKit authorization: \(error)")
}
DispatchQueue.main.async {
completion(success, error)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment