应用程序终止时的 Healthkit 后台交付

Posted

技术标签:

【中文标题】应用程序终止时的 Healthkit 后台交付【英文标题】:Healthkit background delivery when app is terminated 【发布时间】:2021-03-27 10:56:53 【问题描述】:

当应用程序终止但无法运行时,我正在使用这行代码获取每日步数。为了检查这一点,我添加了本地通知,

我添加了后台获取功能。 但是仍然无法正常工作,所以如果我做错了什么,请告诉我。谢谢

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!)
                                            
    )
   
   

【问题讨论】:

【参考方案1】:

为了提高电池寿命和应用程序性能,苹果对后台进程进行了限制,我们无法控制后台获取事件,我们可以控制执行时间。 Apple 根据使用情况授予对应用程序的访问权限,请观看此 WWDC-2019 会议https://developer.apple.com/videos/play/wwdc2019/707/,它将为您提供如何使用后台获取。

【讨论】:

以上是关于应用程序终止时的 Healthkit 后台交付的主要内容,如果未能解决你的问题,请参考以下文章

在几秒钟内多次调用 Healthkit 后台交付

在几秒钟内多次调用 Healthkit 后台交付

如何使用 HealthKit 后台交付?

HealthKit 后台交付

HealthKit 后台交付在一分钟内运行多次

HealthKit 后台交付在一分钟内运行多次