Hello I\'m trying to setup the health store observer with background delivery enabled. My problem is that it won\'t deliver anything when the screen is locked. I have simpli
I was able to get this to work observing weight and blood glucose changes to HealthKit.
In ApplicationDelegate:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
GlobalHealthManager.startObservingWeightChanges()
return true
}
HealthManager.swift
let past = NSDate.distantPast() as NSDate
let now = NSDate()
return HKQuery.predicateForSamplesWithStartDate(past, endDate:now, options: .None)
}()
//here is my query:
lazy var query: HKObserverQuery = {[weak self] in
let strongSelf = self!
return HKObserverQuery(sampleType: strongSelf.weightQuantityType,
//predicate: strongSelf.longRunningPredicate,
predicate : nil, //all samples delivered
updateHandler: strongSelf.weightChangedHandler)
}()
func startObservingWeightChanges(){
healthKitStore?.executeQuery(query)
healthKitStore?.enableBackgroundDeliveryForType(weightQuantityType,
frequency: .Immediate,
withCompletion: {(succeeded: Bool, error: NSError!) in
if succeeded{
println("Enabled background delivery of weight changes")
} else {
if let theError = error{
print("Failed to enable background delivery of weight changes. ")
println("Error = \(theError)")
}
}
})
}
/** this should get called in the background */
func weightChangedHandler(query: HKObserverQuery!,
completionHandler: HKObserverQueryCompletionHandler!,
error: NSError!){
NSLog(" Got an update Here ")
/** this function will get called each time a new weight sample is added to healthKit.
//Here, I need to actually query for the changed values..
//using the standard query functions in HealthKit..
//Tell IOS we're done... updated my server, etc.
completionHandler()
}
}