1

I have a function that gathers step data, but I need a way to make it wait for its query to finish before it loops. I realize there are other questions about this problem, but I can't figure out how to fix it. The function is below:

func stepsAllTime(completion: (Double, NSError?) -> () ) {
    var stopStart = true
    while stopStart {

        x += -1
        // The type of data we are requesting
        let sampleType = HKSampleType.quantityTypeForIdentifier(HKQuantityTypeIdentifierStepCount)
        var daysAgo = x
        var daysSince = x + 1
        var daysSinceNow = -1 * daysAgo
        checker = allTimeSteps.count

        // Our search predicate which will fetch data from now until a day ago
        let samplePredicate = HKQuery.predicateForSamplesWithStartDate(NSCalendar.currentCalendar().dateByAddingUnit(.CalendarUnitDay, value: daysAgo, toDate: NSDate(), options: nil), endDate: NSCalendar.currentCalendar().dateByAddingUnit(.CalendarUnitDay, value: daysSince, toDate: NSDate(), options: nil), options: .None)

        // The actual HealthKit Query which will fetch all of the steps and sub them up for us.
        let stepQuery = HKSampleQuery(sampleType: sampleType, predicate: samplePredicate, limit: 0, sortDescriptors: nil) { query, results, error in
            var steps: Double = 0


            if results?.count > 0 {
                for result in results as! [HKQuantitySample] {
                    steps += result.quantity.doubleValueForUnit(HKUnit.countUnit())
                }
            }

            completion(steps, error)
            self.allTimeStepsSum += steps
            self.allTimeSteps.append(steps)
            println("New Sum:")
            println(self.allTimeStepsSum)
            println("Days Since Today:")
            println(daysSinceNow)
            if !(self.allTimeStepsTotal > self.allTimeStepsSum) {
                stopStart = false
            }
        }
        if allTimeStepsTotal > allTimeStepsSum {

            self.healthKitStore.executeQuery(stepQuery)

        }

    }

}

How can this be done? Is there some sort of "On Complete" function in Swift?

1
  • Just to be clear... you want your stepQuery completion closure to be called before your next while stopStart pass executes? Commented Jul 21, 2015 at 23:39

2 Answers 2

1

I'm assuming that my comment was accurate. You'd probably want to take a look at a recursive pattern, something like this:

import HealthKit

class Person {

    var nbSteps: Double = 0

    func fetchInfo() -> Void {
        let sampleType = HKSampleType()
        let samplePredicate: NSPredicate? = nil // Your predicate
        let stepQuery = HKSampleQuery(
            sampleType: sampleType,
            predicate: samplePredicate,
            limit: 0,
            sortDescriptors: nil) { (sampleQuery, object, error) -> Void in
                self.nbSteps += 1 // or the value you're looking to add

                dispatch_async(dispatch_get_main_queue(), { () -> Void in // Dispatch in order to keep things clean
                    self.fetchInfo()
                })
        }
    }

}
Sign up to request clarification or add additional context in comments.

Comments

1

You can make the program to wait till the query finishes by implementing callbacks.

You can read more about it in the following blog post http://www.charles-socrates-chandler.com/blog/2015/2/10/callbacks-in-swift

1 Comment

In case you haven't noticed, I already have this in my function, and it hasn't helped.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.