ios - How to check when HealthKit function has been completed (Swift) -
well, title says all, , haven't been able find answer anywhere works me turning stackoverflow. trying users step count , assign value uilabel. here of code (please note function contained in class result label not within scope of function):
func readtodayhealthdata() -> int { var stepcount: int = 0 func getstepshealthdata() { let stepsunit = hkunit.countunit() let sumoption = hkstatisticsoptions.cumulativesum let stepshealthdataquery = hkstatisticsquery(quantitytype: stepshealth, quantitysamplepredicate: predicate, options: sumoption) { query, results, error in if let sumquantity = results?.sumquantity() { dispatch_async(dispatch_get_main_queue(), { stepcount = sumquantity.doublevalueforunit(stepsunit) * 2 }) } } healthkitstore?.executequery(stepshealthdataquery) } return stepcount } //set uilabel value //**this code in view controller in separate class result label not within scope of function.** mylabel.text = string(readtodayhealthdata)
then when run app on actual device see label text zero, , know fact have done walking today :). so, think issue when try set labels value function hasn't finished executing.
i know because when use delay function , wait 2 seconds end getting value, if don't wait value of zero.
so main question is: how check when function completely finished executing?
the thing operation you're using async, need handle properly, have 2 options here:
update
uilabel
incompletionhandler
inside functiongetstepshealthdata
in main thread because going update ui, in way:func getstepshealthdata() { var stepcount: int = 0 let stepsunit = hkunit.countunit() let sumoption = hkstatisticsoptions.cumulativesum let stepshealthdataquery = hkstatisticsquery(quantitytype: stepshealth, quantitysamplepredicate: predicate, options: sumoption) { query, results, error in if let sumquantity = results?.sumquantity() { dispatch_async(dispatch_get_main_queue(), { stepcount = sumquantity.doublevalueforunit(stepsunit) * 2 //set uilabel value mylabel.text = string(stepcount) }) } } healthkitstore?.executequery(stepshealthdataquery) }
and don't need return anything.
if want return step counts function need play little closures , modify function in following way:
func getstepshealthdata(completion: (steps: int) -> ()) { var stepcount: int = 0 let stepsunit = hkunit.countunit() let sumoption = hkstatisticsoptions.cumulativesum let stepshealthdataquery = hkstatisticsquery(quantitytype: stepshealth, quantitysamplepredicate: predicate, options: sumoption) { query, results, error in if let sumquantity = results?.sumquantity() { stepcount = sumquantity.doublevalueforunit(stepsunit) * 2 completion(stepcount) } } healthkitstore?.executequery(stepshealthdataquery) }
and can call in way outside:
self.getstepshealthdata() { (steps) -> void in dispatch_async(dispatch_get_main_queue(), { //set uilabel value mylabel.text = string(stepcount) }) }
i hope you.
Comments
Post a Comment