deep ios
deep ios

Reputation: 9

Healthkit background delivery when app is terminated

I am using this line of code for getting daily steps when app is terminated but not working. For check this I added the local notification,

I added the capability of Background fetch. But still not working so please let me know if there I am doing something wrong. Thanks

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
   
    UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
    UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .sound, .alert], completionHandler: { (success, error) in
        if (success) {
            DispatchQueue.main.async {
                application.registerForRemoteNotifications()
            }
        }
    })

// self.locationRequest = MyLocationTracker()

    self.authorizeHealthKit { (authorized,  error) -> Void in
        if authorized {
            print("HealthKit authorization received.")
        }
        else {
            print("HealthKit authorization denied!")
            if error != nil {
                print("\(error)")
            }
        }
    }
   
    return true
}

func startObservingHeightChanges() {
   
    let sampleType =  HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)
   
    let query: HKObserverQuery = HKObserverQuery(sampleType: sampleType!, predicate: nil, updateHandler: self.heightChangedHandler)
   
    healthKitStore.execute(query)
    healthKitStore.enableBackgroundDelivery(for: sampleType!, frequency: .immediate, withCompletion: {(succeeded: Bool, error: Error!) in
       
        if succeeded{
            print("Enabled background delivery of weight changes")
        } else {
            if let theError = error{
                print("Failed to enable background delivery of weight changes. ")
                print("Error = \(theError)")
            }
        }
        } as (Bool, Error?) -> Void)
}


func heightChangedHandler(query: HKObserverQuery!, completionHandler: HKObserverQueryCompletionHandler!, error: Error!) {
   
    print("backgound test")
    let content = UNMutableNotificationContent()
    content.body = NSString.localizedUserNotificationString(forKey: "App working on background", arguments: nil)
    content.sound = UNNotificationSound.default
    content.categoryIdentifier = "notify-test"
   
    let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 1, repeats: false)
    let request = UNNotificationRequest.init(identifier: "notify-test", content: content, trigger: trigger)
   
    let center = UNUserNotificationCenter.current()
    center.add(request)
    completionHandler()
}

func authorizeHealthKit(completion: ((_ success:Bool, _ error:NSError?) -> Void)!) {
   
    if !HKHealthStore.isHealthDataAvailable() {
       
        print("health kit not accessable")
        return;
    }
   
    let healthKitTypesToRead : Set<HKObjectType> = [HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!]
   
   
    healthKitStore.requestAuthorization(toShare: nil,
                                        read: healthKitTypesToRead,
                                        completion: { (success, error) -> Void in
                                            if success {
                                                print("success authorization1")
                                                DispatchQueue.main.async(execute: self.startObservingHeightChanges)
                                                completion(success,error as NSError?)
                                            } else {
                                                print("error")
                                                print(error!)
                                            }
    })
   
   
}

}

Upvotes: 0

Views: 640

Answers (1)

Sumit
Sumit

Reputation: 41

To improve battery life and app performance apple has put the restriction on background processes, we don't have any control over background fetch event we can the execution time. Apple gives access to the app based on the usage, please watch this WWDC-2019 session https://developer.apple.com/videos/play/wwdc2019/707/ it will provide you how to use background fetch.

Upvotes: 1

Related Questions