Search code examples
iosswiftconcurrencycore-motion

iOS Concurrency issue: method returned before got the pedometer data


like the code below, when I want to return a pedometer data through a method for some connivence, but the method returned earlier than the data be retrieved.I think this maybe a concurrency issue. How could I return the data in a right way for future use?Thx

 func queryPedometerTodayTotalData() -> Int {
     var pedometerDataOfToday: CMPedometerData?
        self.queryPedometerDataFromDate(NSDate.today()!, toDate: NSDate(), withHandler: { (pedometerData, error) in
            pedometerDataOfToday = pedometerData!
            print("this print after got data in a background thread:\(pedometerDataOfToday)")
        })
        print("This should print before last print, and there haven't got the data now: \(pedometerDataOfToday)")
    return pedometerDataOfToday
}

Solution

  • You're right about it being a concurrency issue. You should use the result inside the handler of the queryPedometerDataFromDate. One way of achieving this would be to use a completion block for your queryPedometerTodayTotalData method instead of having it return a value, like this:

    func queryPedometerTodayTotalData(completion:((CMPedometerData?)->())) {
        var pedometerDataOfToday: CMPedometerData?
        self.queryPedometerDataFromDate(NSDate.today()!, toDate: NSDate(), withHandler: { (pedometerData, error) in
            pedometerDataOfToday = pedometerData!
            completion(pedometerData)
        })
    }
    
    func testQueryPedometerTodayTotalData() {
        self.queryPedometerTodayTotalData { (data) in
            print(data)
        }
    }