当用户步行1公里和5公里时激活我的应用程序,以此类推。当应用程序未运行或处于后台时,在ios swift中使用healthkit

当用户步行1公里和5公里时激活我的应用程序,以此类推。当应用程序未运行或处于后台时,在ios swift中使用healthkit,ios,swift3,healthkit,Ios,Swift3,Healthkit,我遵循了这个问题的答案- 在stackoverflow上,但没有达到我的目标 我想通知用户使用本地通知时,他/她走了1公里,当应用程序是在后台,而不是运行状态。 我仍然无法从背景中读出与Healthkit的距离 但当应用程序在前台时,只有我的代码起作用,代码也一样 let healthKitStore = HKHealthStore() let distanceType = HKObjectType.quantityType(forIdentifier: HKQuantityTypeId

我遵循了这个问题的答案- 在stackoverflow上,但没有达到我的目标

我想通知用户使用本地通知时,他/她走了1公里,当应用程序是在后台,而不是运行状态。 我仍然无法从背景中读出与Healthkit的距离

但当应用程序在前台时,只有我的代码起作用,代码也一样

let healthKitStore = HKHealthStore()
    let distanceType = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.distanceWalkingRunning)!
    let query:HKObserverQuery = HKObserverQuery(sampleType: distanceType, predicate: nil) { (query, HKObserverQueryCompletionHandler, error) in
        //here I schedule my local notification
        // I want to read the distance here and also want to notify user.
        self.callLocalNotification(1)
        HKObserverQueryCompletionHandler()
    }
    healthKitStore?.execute(query)
    healthKitStore?.enableBackgroundDelivery(for: distanceType, frequency: .immediate, withCompletion: { (succeeded, error) in
        if succeeded{
            print("Enabled background delivery of Distance changes")
        } else {
            if let theError = error{
                print("Failed to enable background delivery of Distance changes.")
                print("Error = \(theError)")
            }
        }
    })

func callLocalNotification(_ distance:Int)
{
    // Request Notification Settings
    UNUserNotificationCenter.current().getNotificationSettings { (notificationSettings) in
        switch notificationSettings.authorizationStatus {
        case .notDetermined:
            self.requestAuthorization(completionHandler: { (success) in
                guard success else { return }

                // Schedule Local Notification
                self.scheduleLocalNotification(distance)
            })
        case .authorized:
            // Schedule Local Notification
            self.scheduleLocalNotification(distance)
        case .denied:
            print("Application Not Allowed to Display Notifications")
        }
    }