后台任务未运行

时间:2020-07-24 15:18:35

标签: ios swift healthkit background-task

我正在尝试在后台检查某些HealthKit数据并在满足某些条件时发送本地通知。

我添加了后台获取功能,并将任务的ID添加到info.plist

这是后台任务代码:

func application(_ application: UIApplication,
                     didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        // other setups

        self.setupHealthKit()

        self.setupBackgroundTasks()
        
        return true
    }

fileprivate func setupHealthKit() {
        
        HealthKitHelper.shared.executeObserverQuery(for: HealthKitTypes.activeEnergy,
                                                predicate: nil)
        .sink(receiveCompletion: {
            completion in
            switch completion {
            case .failure(let error):
                print("observer query execution failed with error: \(error.localizedDescription)")
                EventLogger.BackgroundDelivery.logObserverQueryError(error: error.localizedDescription)
            case .finished:
                print("observer query executed.")
            }
        }, receiveValue: {
            query, handler in
            // we have some updates
            
            EventLogger.BackgroundDelivery.logObserverQueryResultInBackground()
            
            // check if there is a new sleep session
            
            let queue = OperationQueue()
            
            let operations = self.getBackgroundOperations()
            
            let last = operations.last!
            last.completionBlock = {
                handler()
            }
            
            queue.addOperations(operations, waitUntilFinished: false)
            
        })
        .store(in: &self.subscriberStore)
        
        HealthKitHelper.shared.enableBackgroundDelivery(for: HealthKitTypes.activeEnergy,
                                                        frequency: .hourly)
            .sink(receiveCompletion: {
                completion in
                switch completion {
                case .failure(let error):
                    print("failed to enable bg delivery with error: \(error.localizedDescription)")
                case .finished:
                    print("delivery enable finished.")
                }
            }, receiveValue: {
                status in
                print("delivery enable success status: \(status)")
            })
            .store(in: &self.subscriberStore)
        
    }
    
func setupBackgroundTasks() {
        
        let status = BGTaskScheduler.shared.register(forTaskWithIdentifier: self.BACKGROUND_FETCH_TASK_ID,
                                                     using: nil) {
            task in
            
            self.handleBackgroundAppRefresh(task as! BGAppRefreshTask)
            
        }
        
    }

我只是在后台任务中发送本地通知,以查看其是否有效。 现在,我可以在调试器中运行后台任务,但是它永远不会被系统执行。

我也不知道在后台获取新的医疗工具包样本的最佳方法是什么。

1 个答案:

答案 0 :(得分:0)

您必须使用 HKObserverQuery 在后台查询健康数据。