Can I save value in a completion Handler

2019-07-27 11:27发布

here is the thing, I wants to save the today steps into Core Data in completionHandler. But while I load this value,the complier shows it a nil. any solution?

 func fetchDataOfQuantityType(startDate: NSDate, endDate: NSDate, quantityType: HKQuantityType, completion:((NSArray, NSError!) -> Void)!)  {

    // initial a predicate with startDate and endDate
    let predicate = HKQuery.predicateForSamplesWithStartDate(startDate, endDate: endDate, options: HKQueryOptions.StrictStartDate)

    // initialize a HKStatisticsQuery
    let query: HKStatisticsQuery = HKStatisticsQuery(quantityType: quantityType, quantitySamplePredicate: predicate, options: HKStatisticsOptions.CumulativeSum, completionHandler: { (query, results, error) in

        if error != nil { // if there is an error print it
            println("there is a \(error) occur")
            return
        }
        // Mark: - Saving the data in to Core data

        var todaySteps = results.sumQuantity().doubleValueForUnit(HKUnit.countUnit())
        println("The totalstep for today is \(todaySteps)")
            var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
            var context: NSManagedObjectContext = appDel.managedObjectContext!
            var newUser = NSEntityDescription.insertNewObjectForEntityForName("User", inManagedObjectContext: context) as NSManagedObject
            newUser.setValue(todaySteps, forKey: "todaysteps")
            })
    self.healthstore.executeQuery(query)
}

1条回答
Lonely孤独者°
2楼-- · 2019-07-27 12:20

This looks like you're not saving the context. Try

var error: NSError?
context.save(&error)

after you've set the value.

查看更多
登录 后发表回答