0

I checked below link Healthkit background delivery when app is not running

and follow all instruction to get update from my walk count in background mode and if it detect step, send information to my personal server. but it never send to my server even if I walk many hours .

my iOS version is 15.5 and watch os version is 8.6 which is newest version for all

on swiftUI we don't have a--delegate so, I wrote enableDelivery and HKObserverQuery function in main view

I wrote code based on apple's sample code for coffee tracker

import SwiftUI

import HealthKit
import os
import CoreData
// The Coffee Tracker app's main view.
struct CoffeeTrackerView: View {
    
    @EnvironmentObject var coffeeData: CoffeeData
    @State var showDrinkList = false
    
    private var backgroundObserver: HKObserverQuery? = nil
    
    private let store = HKHealthStore()

    // Properties that determine whether the store is available and ready to use.
    private let isAvailable = HKHealthStore.isHealthDataAvailable()
    private var isAuthorized = false
    // Lay out the view's body.
    var body: some View {
        
        // Use a timeline view to update the caffeine dose every minute.
        // This works both when the user's interacting with the app,
        // and when it's in Always On mode.
        TimelineView(.everyMinute) { context in
            VStack {
                
                // Display the current amount of caffeine in the user's body.
                Text(coffeeData.mgCaffeineString(atDate: context.date) + " mg")
                    .font(.body)
                    .fontWeight(.bold)
                    .foregroundColor(colorForCaffeineDose(atDate: context.date))
                Text("Current Caffeine Dose")
                    .font(.footnote)
                Divider()
                
                // Display how much the user has drunk today,
                // using the equivalent number of 8 oz. cups of coffee.
                Text(coffeeData.totalCupsTodayString + " cups")
                    .font(.body)
                    .fontWeight(.bold)
                    .foregroundColor(colorForDailyDrinkCount())
                Text("Equivalent Drinks Today")
                    .font(.footnote)
                Spacer()
                
                // Display a button that lets the user record new drinks.
                Button(action: { self.showDrinkList.toggle() }) {
                    Image("add-coffee")
                        .renderingMode(.template)
                }
            }.onAppear{
                let steps: HKObjectType = HKObjectType.quantityType(forIdentifier: .stepCount)!
                    if store.authorizationStatus(for: steps) != HKAuthorizationStatus.notDetermined {
                        store.enableBackgroundDelivery(for: steps, frequency: .immediate, withCompletion: { (worked, error) in
                            //registers for background data
                            let myUrl = URL(string:"https://my_server/testpage?q=processUpdate22")
                              var request = URLRequest(url: myUrl!)
                              request.httpMethod="GET"
                              let task = URLSession.shared.dataTask(with: request){
                                  (data:Data?,response:URLResponse?,error:Error?) in
                                  if error != nil {
                                      print("error \(error)")
                                      return
                                  }else{
                                      print("no error")
                                  }
                              }
                              task.resume()
                            if error != nil {
                                print(error)
                            }
                        })
                        let sampleType = HKSampleType.quantityType(forIdentifier: HKQuantityTypeIdentifier.stepCount)!
                        let query = HKObserverQuery(sampleType: sampleType, predicate: nil) {
                            query, completionHandler, error in
                                      let myUrl = URL(string:"https://my_server/testpage?q=processUpdatee")
                                        var request = URLRequest(url: myUrl!)
                                        request.httpMethod="GET"
                                        let task = URLSession.shared.dataTask(with: request){
                                            (data:Data?,response:URLResponse?,error:Error?) in
                                            if error != nil {
                                                print("error \(error)")
                                                return
                                            }
                                        }
                                        task.resume()
                            if error != nil {
                                print(error)
                                abort()
                            }

                            // Take whatever steps are necessary to update your app's data and UI
                            // This may involve executing other queries
        //                    self.getSteps(completion: { (stepCount) in
        //                        print("Step count was updated to \(stepCount)")
        //                    })
                            completionHandler()
                        }

                        store.execute(query)
                    }
            }
        }
        .sheet(isPresented: $showDrinkList) {
            DrinkListView().environmentObject(self.coffeeData)
        }
    }
Pedro J
  • 281
  • 5
  • 14
  • 1
    I was not able to find your actual query in your code snippet. `HKObserverQuery` only lets you know that new samples were added for the given type. You must run a query inside its callback to actually fetch this new data. Also, remember to call `completionHandler()` on all exit points, even when errors occur. If you dont call it, iOS will stop waking up your app. – gggava Jun 14 '22 at 12:22
  • 1
    HKHealthStore can't be init in the View struct, a new instance will be made every time. Notice how in the sample its a global inside HealthKitController.swift – malhal Jun 14 '22 at 13:10

0 Answers0