1

I have followed the answers of this question - Healthkit background delivery when app is not running on stackoverflow but not achieved my goal.

I want to notify user using local notification when he/she walked 1 km exact, when app is in background and not running state. I am still not able to read the distance from Healthkit in background as well.

But when app is in foreground then only my code works and the code is as blow

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")
        }
    }
Sushobhit
  • 305
  • 4
  • 18

0 Answers0