Skip to content

Instantly share code, notes, and snippets.

@phatblat
Last active October 10, 2024 18:40
Show Gist options
  • Save phatblat/654ab2b3a135edf905f4a854fdb2d7c8 to your computer and use it in GitHub Desktop.
Save phatblat/654ab2b3a135edf905f4a854fdb2d7c8 to your computer and use it in GitHub Desktop.
Example of creating HKObserverQuery and enabling background delivery for multiple HKObjectType
@UIApplicationMain
final class AppDelegate: UIResponder, UIApplicationDelegate {
let healthKitManager = HealthKitManager()
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
if onboardingComplete {
healthKitManager.requestAccessWithCompletion() { success, error in
if success { print("HealthKit access granted") }
else { print("Error requesting access to HealthKit: \(error)") }
}
}
return true
}
}
final class FirstViewControllerAfterOnboardingFlow: UIViewController {
let healthKitManager = HealthKitManager()
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
onboardingComplete = true
healthKitManager.requestAccessWithCompletion() { success, error in
if success { print("HealthKit access granted") }
else { print("Error requesting access to HealthKit: \(error)") }
}
}
}
typealias AccessRequestCallback = (success: Bool, error: NSError?) -> Void
/// Helper for reading and writing to HealthKit.
class HealthKitManager {
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: AccessRequestCallback) {
guard deviceSupportsHealthKit() else {
debugPrint("Can't request access to HealthKit when it's not supported on the device.")
return
}
let writeDataTypes = dataTypesToWrite()
let readDataTypes = dataTypesToRead()
healthStore.requestAuthorizationToShareTypes(writeDataTypes, readTypes: readDataTypes) { [weak self] (success: Bool, error: NSError?) in
guard let strongSelf = self else { return }
if success {
debugPrint("Access to HealthKit data has been granted")
strongSelf.readHealthKitData()
strongSelf.setUpBackgroundDeliveryForDataTypes(readDataTypes)
} else {
debugPrint("Error requesting HealthKit authorization: \(error)")
}
dispatch_async(dispatch_get_main_queue()) {
completion(success: success, error: error)
}
}
}
}
// MARK: - Private
private extension HealthKitManager {
/// Initiates an `HKAnchoredObjectQuery` for each type of data that the app reads and stores
/// the result as well as the new anchor.
func readHealthKitData() { /* ... */ }
/// Sets up the observer queries for background health data delivery.
///
/// - parameter types: Set of `HKObjectType` to observe changes to.
private func setUpBackgroundDeliveryForDataTypes(types: Set<HKObjectType>) {
for type in types {
guard let sampleType = type as? HKSampleType else { print("ERROR: \(type) is not an HKSampleType"); continue }
let query = HKObserverQuery(sampleType: sampleType, predicate: nil) { [weak self] (query: HKObserverQuery, completionHandler: HKObserverQueryCompletionHandler, error: NSError?) in
debugPrint("observer query update handler called for type \(type), error: \(error)")
guard let strongSelf = self else { return }
strongSelf.queryForUpdates(type)
completionHandler()
}
healthStore.executeQuery(query)
healthStore.enableBackgroundDeliveryForType(type, frequency: .Immediate) { (success: Bool, error: NSError?) in
debugPrint("enableBackgroundDeliveryForType handler called for \(type) - success: \(success), error: \(error)")
}
}
}
/// Initiates HK queries for new data based on the given type
///
/// - parameter type: `HKObjectType` which has new data avilable.
private func queryForUpdates(type: HKObjectType) {
switch type {
case HKObjectType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierDateOfBirth)!:
debugPrint("HKCharacteristicTypeIdentifierDateOfBirth") // not currently supported rdar://22221216
case HKObjectType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierBiologicalSex)!:
debugPrint("HKCharacteristicTypeIdentifierBiologicalSex") // not currently supported rdar://22221216
case HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)!:
debugPrint("HKQuantityTypeIdentifierBodyMass")
case HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight)!:
debugPrint("HKQuantityTypeIdentifierHeight")
case is HKWorkoutType:
debugPrint("HKWorkoutType")
default: debugPrint("Unhandled HKObjectType: \(type)")
}
}
/// Types of data that this app wishes to read from HealthKit.
///
/// - returns: A set of HKObjectType.
private func dataTypesToRead() -> Set<HKObjectType> {
return Set(arrayLiteral:
HKObjectType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierDateOfBirth)!,
HKObjectType.characteristicTypeForIdentifier(HKCharacteristicTypeIdentifierBiologicalSex)!,
HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)!,
HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight)!,
HKObjectType.workoutType()
)
}
/// Types of data that this app wishes to write to HealthKit.
///
/// - returns: A set of HKSampleType.
private func dataTypesToWrite() -> Set<HKSampleType> {
return Set(arrayLiteral:
HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass)!,
HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight)!,
HKObjectType.workoutType()
)
}
}

Copyright (c) 2016 Ben Chatelain

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

@mohammad-rahchamani
Copy link

do we need to enable background mode to get updates when the app is not running or enabling background delivery will be enough?

@phatblat
Copy link
Author

My understanding is that invoking enableBackgroundDeliveryForType:frequency:withCompletion: is all that is required for receiving data from HealthKit in the background. However, note that this should be done every time the app is launched in the application(_:didFinishLaunchingWithOptions:) method. See Receive Background Deliveries, which doesn't say anything about background task completion or background modes (though some people have tried using these with mixed results).

I haven't actually used these API in a real app, so I can't say for sure.

@kitlogan
Copy link

Hi all,

Thank you for this, it will be very helpful. Quick question:

In the delegate you have "if onboardingComplete {...}".

How can I go about setting a state/ variable like this?

  1. How can this variable get set from Views that come after the delegate?
  2. How can I make sure the variable value persists between app launches? If onboarding is complete that should be the case for every time they launch the app afterwards too?

Thank you!

@phatblat
Copy link
Author

@kitlogan User Defaults is a simple local key-value store where you can persist simple data like that.

@kitlogan
Copy link

Thanks!

@kitlogan User Defaults is a simple local key-value store where you can persist simple data like that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment