ios - HealthKit Observer not working while app is in background mode -


i have followed apple docs , several threads on stackoverflow on how achieve background fetching of data health store. far have:

  • added healthkit entitlement appid
  • added required background modes
  • added code appdelegate.swift apple suggest (the snippet below not following oop facility state way here)

this code (swift): if answer in obj-c , works, please state well, have translate it, that's no problem.

appdelegate.swift

var healthstore: hkhealthstore? var bpmsamples: [hkquantitysample]?  func application(application: uiapplication, didfinishlaunchingwithoptions launchoptions: [nsobject: anyobject]?) -> bool {     let datatypestowrite = [ ]     let datatypestoread = [         hkquantitytype.quantitytypeforidentifier(hkquantitytypeidentifierheartrate),         hkquantitytype.quantitytypeforidentifier(hkquantitytypeidentifierbodymassindex),         hkcharacteristictype.characteristictypeforidentifier(hkcharacteristictypeidentifierdateofbirth)     ]     if self.healthstore == nil {         self.healthstore = hkhealthstore()     }     self.healthstore?.requestauthorizationtosharetypes(nsset(array: datatypestowrite [anyobject]) set<nsobject>,         readtypes: nsset(array: datatypestoread) set<nsobject>, completion: {             (success, error) in             if success {                 self.addqueryobserver()                 println("user completed authorisation request.")             } else {                 println("the user cancelled authorisation request. \(error)")             }     })     return true }  func addqueryobserver(){     let sampletype =     hkobjecttype.quantitytypeforidentifier(hkquantitytypeidentifierheartrate)      let query = hkobserverquery(sampletype: sampletype, predicate: nil) {         query, completionhandler, error in         if error != nil {             // perform proper error handling here...             println("*** error occured while setting stepcount observer. \(error.localizeddescription) ***")             abort()         }         println("query running")          self.performqueryforheartbeatsamples()         completionhandler()     }     healthstore?.executequery(query)     healthstore?.enablebackgrounddeliveryfortype(sampletype, frequency:.immediate, withcompletion:{         (success:bool, error:nserror!) -> void in         let authorized = self.healthstore!.authorizationstatusfortype(sampletype)         println("health callback success", success)         println("health callback authorized", sampletype)     })     if hkhealthstore.ishealthdataavailable() == false {         println("health data not available")         return     } else {         println("health ok")         self.performqueryforheartbeatsamples()     } }  // mark: - healthstore utility methods func performqueryforheartbeatsamples() {     let enddate = nsdate()     let startdate = nscalendar.currentcalendar().datebyaddingunit(.calendarunitmonth, value: -2, todate: enddate, options: nil)      var heartrate : hkquantitytype = hkquantitytype.quantitytypeforidentifier(hkquantitytypeidentifierheartrate)      let predicate = hkquery.predicateforsampleswithstartdate(startdate, enddate: enddate, options: .none)     let query = hksamplequery(sampletype: heartrate, predicate: predicate, limit: 0, sortdescriptors: nil, resultshandler: {         (query, results, error) in         if results == nil {             println("there error running query: \(error)")         }         dispatch_async(dispatch_get_main_queue()) {             self.bpmsamples = results as? [hkquantitysample]             let heartrateunit: hkunit = hkunit.countunit().unitdividedbyunit(hkunit.minuteunit())             if self.bpmsamples?.count > 0 {                 if let sample = self.bpmsamples?[self.bpmsamples!.count - 1] {                     println(sample.quantity!.description)                     let quantity = sample.quantity                     var value = quantity.doublevalueforunit(heartrateunit)                     println("bpm: \(value)")                 }             }             else {                 println("no data")             }         }     })     self.healthstore?.executequery(query) } 

so, problem receive updates when resume app background active state manually.. hkobserverquery doesn't seems working me while on background mode.

any suggestions?

in experiences, frequency ".immediate" doesn't work well. handler of queries inserted background queue. if matching samples added or ios busy, immediate frequency doesn't work well.

in addition, cannot use hksamplequery in hkobserverquery. updatehandler of hkobserverquery may work, resulthandler of hksamplequery not. handler of observer query can executed in background mode 1 of sample query cannot executed in background mode.

you should know only hkobserverquery can used in background


Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -