Healthkit background delivery is not working

https://developer.apple.com/documentation/healthkit/hkhealthstore/1614175-enablebackgrounddelivery, as Apple official described the technical documentation, We can read the health data in HealthStore when the application is not started or in the Kill state, when the data in the health App is updated. But it doesn't work for me, I don't know why, I hope I can get the answer here, thank you very much!

Here is my code:


typealias AccessRequestCallback = (_ success: Bool, _ error: Error?) -> Void

/// Helper for reading and writing to HealthKit.
class HealthKitManager: NSObject {
   
  static let shared = HealthKitManager()
   
  private override init() {}
   
  private let healthStore = HKHealthStore()
  /// Requests access to all the data types the app wishes to read/write from HealthKit.
  /// On success, data is queried immediately and observer queries are set up for background
  /// delivery. This is safe to call repeatedly and should be called at least once per launch.
  func requestAccessWithCompletion(completion: @escaping AccessRequestCallback) {
    guard HKHealthStore.isHealthDataAvailable() else {
      debugPrint("Can't request access to HealthKit when it's not supported on the device.")
      return
    }

    let writeDataTypes = dataTypesToWrite()
    let readDataTypes = dataTypesToRead()
     
    healthStore.requestAuthorization(toShare: writeDataTypes, read: readDataTypes) { [weak self] success, error in
      guard let strongSelf = self else { return }
      if success {
        debugPrint("Access to HealthKit data has been granted")
        strongSelf.readHealthKitData()
        strongSelf.setUpBackgroundDeliveryForDataTypes(types: readDataTypes)
      } else {
        debugPrint("Error requesting HealthKit authorization: \(error?.localizedDescription ?? "")")
      }
       
      DispatchQueue.main.async {
        completion(success,error)
      }
    }
  }
   
}

// MARK: - Private
private extension HealthKitManager {
  /// Initiates an `HKAnchoredObjectQuery` for each type of data that the app reads and stores
  /// the result as well as the new anchor.
  func readHealthKitData() {
    debugPrint("===============readHealthKitData================")
//    HealthKitManager.shared.addLocalPush(title: "readHealthKitData")
  }

  /// Sets up the observer queries for background health data delivery.
  ///
  /// - parameter types: Set of `HKObjectType` to observe changes to.
  private func setUpBackgroundDeliveryForDataTypes(types: Set<HKObjectType>) {
    for type in types {
      guard let sampleType = type as? HKSampleType else {
        debugPrint("ERROR: \(type) is not an HKSampleType");
        continue
      }
      var query: HKQuery!
      query = HKObserverQuery(sampleType: sampleType, predicate: nil) { [weak self] query, completionHandler, error in
        if error != nil {
          debugPrint("observer query update handler called for type \(type), error: \(error?.localizedDescription ?? "")")
          return
        }
        guard let strongSelf = self else { return }
        strongSelf.queryForUpdates(type: type)
        completionHandler()
      }
      healthStore.execute(query)
      healthStore.enableBackgroundDelivery(for: type, frequency: .immediate) { success, error in
        if error != nil {
          debugPrint("enableBackgroundDeliveryForType handler called for \(type) - success: \(success), error: \(error?.localizedDescription ?? "")")
          return
        }
        debugPrint("enableBackgroundDeliveryForType: \(type)")
      }
    }
  }

  /// Initiates HK queries for new data based on the given type
  ///
  /// - parameter type: `HKObjectType` which has new data avilable.
  private func queryForUpdates(type: HKObjectType) {
//    self.addLocalPush(title: "queryForUpdates")
    switch type {
    case HKObjectType.quantityType(forIdentifier: .bodyMass):
      debugPrint("HKQuantityTypeIdentifier-BodyMass")
    case HKObjectType.quantityType(forIdentifier: .height):
      debugPrint("HKQuantityTypeIdentifier-Height")
    case HKObjectType.quantityType(forIdentifier: .stepCount):
      debugPrint("HKQuantityTypeIdentifier-StepCount")
    case is HKWorkoutType:
      debugPrint("HKWorkoutType")
    default: debugPrint("Unhandled HKObjectType: \(type)")
    }
  }

  /// Types of data that this app wishes to read from HealthKit.
  ///
  /// - returns: A set of HKObjectType.
  private func dataTypesToRead() -> Set<HKObjectType> {
    if #available(iOS 14.0, *) {
      return Set(arrayLiteral:
            HKObjectType.quantityType(forIdentifier: .bodyMass)!,
            HKObjectType.quantityType(forIdentifier: .height)!,
            HKObjectType.categoryType(forIdentifier: .handwashingEvent)!,
            HKObjectType.quantityType(forIdentifier: .stepCount)!,
            HKObjectType.quantityType(forIdentifier: .distanceCycling)!,
            HKObjectType.workoutType())
    } else {
      return Set(arrayLiteral:
            HKObjectType.quantityType(forIdentifier: .bodyMass)!,
            HKObjectType.quantityType(forIdentifier: .height)!,
            HKObjectType.quantityType(forIdentifier: .stepCount)!,
            HKObjectType.quantityType(forIdentifier: .distanceCycling)!,
            HKObjectType.workoutType())
    }
  }

  /// Types of data that this app wishes to write to HealthKit.
  ///
  /// - returns: A set of HKSampleType.
  private func dataTypesToWrite() -> Set<HKSampleType> {
    if #available(iOS 14.0, *) {
      return Set(arrayLiteral:
            HKObjectType.quantityType(forIdentifier: .bodyMass)!,
            HKObjectType.quantityType(forIdentifier: .height)!,
            HKObjectType.categoryType(forIdentifier: .handwashingEvent)!,
            HKObjectType.quantityType(forIdentifier: .stepCount)!,
            HKObjectType.quantityType(forIdentifier: .distanceCycling)!,
            HKObjectType.workoutType())
    } else {
      return Set(arrayLiteral:
            HKObjectType.quantityType(forIdentifier: .bodyMass)!,
            HKObjectType.quantityType(forIdentifier: .height)!,
            HKObjectType.quantityType(forIdentifier: .stepCount)!,
            HKObjectType.quantityType(forIdentifier: .distanceCycling)!,
            HKObjectType.workoutType())
    }
  }
}

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
     
    window = UIWindow(frame: UIScreen.main.bounds)
     
    let vc: ViewController = .init()
    window?.rootViewController = vc
    window?.makeKeyAndVisible()
     
    healthKitManager.requestAccessWithCompletion() { success, error in
      if success { print("HealthKit access granted") }
      else { print("Error requesting access to HealthKit: \(error?.localizedDescription ?? "")") }
    }
     
    return true
  }
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
     
    window = UIWindow(frame: UIScreen.main.bounds)
     
    let vc: ViewController = .init()
    window?.rootViewController = vc
    window?.makeKeyAndVisible()
     
    healthKitManager.requestAccessWithCompletion() { success, error in
      if success { print("HealthKit access granted") }
      else { print("Error requesting access to HealthKit: \(error?.localizedDescription ?? "")") }
    }
     
    return true
  }
Healthkit background delivery is not working
 
 
Q