Healthkit-在后台方法中返回最新锻炼

时间:2019-05-04 14:25:25

标签: ios swift background-process health-kit

我正在使用以下代码来检测何时在后台将任何新的锻炼添加到healthkit。但是,只要调用该方法,它就会返回自后台传递方法启动以来已记录的所有锻炼。有没有办法只监视新的锻炼类型,而不是全部恢复?

这是我在didFinishLaunching中调用的代码

    func startObservingNewWorkouts() {
    let currentUser = PFUser.current()
    if currentUser != nil {
        let query = PFQuery(className:"UserData")
        query.whereKey("Username", equalTo:currentUser!.username!)
        query.findObjectsInBackground { (objects: [PFObject]?, error: Error?) in
            if let error = error {
                // Log details of the failure
                print(error.localizedDescription)
            } else if let objects = objects {
                // The find succeeded.
                // Do something with the found objects
                for object in objects {
                    UserData = object
                    let sampleType =  HKObjectType.workoutType()

                    //1. Enable background delivery for workouts
                    self.healthKitStore.enableBackgroundDelivery(for: sampleType, frequency: .immediate) { (success, error) in
                        if let unwrappedError = error {
                            print("could not enable background delivery: \(unwrappedError)")
                        }
                        if success {
                            print("background delivery enabled")
                        }
                    }

                    //2.  open observer query
                    let query = HKObserverQuery(sampleType: sampleType, predicate: nil) { (query, completionHandler, error) in

                        self.updateWorkouts() {
                            completionHandler()
                        }


                    }
                    healthStore.execute(query)
                }
            }
        }
    }



}

func updateWorkouts(completionHandler: @escaping () -> Void) {

    var anchor: HKQueryAnchor?

    let sampleType =  HKObjectType.workoutType()

    let anchoredQuery = HKAnchoredObjectQuery(type: sampleType, predicate: nil, anchor: anchor, limit: HKObjectQueryNoLimit) { [unowned self] query, newSamples, deletedSamples, newAnchor, error in

        self.handleNewWorkouts(new: newSamples!, deleted: deletedSamples!)

        anchor = newAnchor

        completionHandler()
    }
    healthStore.execute(anchoredQuery)


}

func handleNewWorkouts(new: [HKSample], deleted: [HKDeletedObject]) {
    print("new sample added = \(new.last?.startDate)")
    userWorkouts = UserData["UserWorkouts"] as? [Dictionary<String,String>] ?? []
    let i = new.last as! HKWorkout
    var userWorkout = [String: String]()
    userWorkout["Description"] = i.description
    userWorkout["Source"] = i.sourceRevision.source.name
    userWorkout["Duration"] = String(format: "%.0f", i.duration)

    userWorkouts.insert(userWorkout, at: 0)
    UserData["UserWorkouts"] = userWorkouts
    UserData.saveInBackground {
        (success: Bool, error: Error?) in
        if (success) {
            self.userDefaults.set(userWorkouts2, forKey: "userWorkouts")
            self.userDefaults.set(Date(),forKey: "lastWorkoutUpdate")

            let content = UNMutableNotificationContent()
            content.title = "New Workout Logged!"
                content.body = "New workout logged from \(i.sourceRevision.source.name)
            content.sound = UNNotificationSound.default
            let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 2, repeats: false)
            let request = UNNotificationRequest(identifier: "notification.id.01", content: content, trigger: trigger)
            UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
            // The object has been saved.
        } else {
            // There was a problem, check error.description
        }
    }
    }

0 个答案:

没有答案