首页 > 解决方案 > iOS后台任务从未启动

问题描述

此代码应该定期安排后台任务。

在设备上运行时,我从来没有看到“后台刷新已启动”日志可以证明系统已经安排了任务。

其他一切运行良好。

当我通过在控制台中输入来使用“强制后台任务启动技巧”时,e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateLaunchForTaskWithIdentifier:@"TaskIdentifier"]我确实看到了正在执行的任务。

我在目标功能中激活了后台获取和后台处理。

那么为什么系统不安排任务呢?

class AppDelegate: UIResponder, UIApplicationDelegate {

    func application(_ application:                                 UIApplication,
                     didFinishLaunchingWithOptions launchOptions:   [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        MSLogger.debug("Application Event : didFinishLaunchingWithOptions")
        
        //  Register the background refresh handler and schedule it
        registerForBackgroundRefresh()
        scheduleNextRefresh()

        return true
    }

    
    //------------------------------------------------------------------------------------------------------------------
    // MARK: -  Background refresh management
    let backgroundTaskIdentifier    = "TaskIdentifier"
    
    func registerForBackgroundRefresh() {
        let crd = BGTaskScheduler.shared.register(forTaskWithIdentifier:  backgroundTaskIdentifier,
                                                  using:                  nil) {
            task in
            self.handleBackgroundRefresh(task: task as! BGAppRefreshTask)
        }
        MSLogger.debug("task registration : \(crd)")
    }
    
    func scheduleNextRefresh() {
        //  Schedule the next refresh for within 2 hours
        let request = BGAppRefreshTaskRequest(identifier: backgroundTaskIdentifier)
        request.earliestBeginDate = Date(timeIntervalSinceNow: 30 /*2 * 3600##*/)
             
        do {
            try BGTaskScheduler.shared.submit(request)
            MSLogger.debug("submit background task request")
        } catch {
            MSLogger.debug("Could not schedule app refresh: \(error.localizedDescription)")
        }
    }
    
    func handleBackgroundRefresh(task: BGAppRefreshTask) {
        MSLogger.debug("background refresh started")
        
        let queue       = OperationQueue()
        queue.maxConcurrentOperationCount = 1
        
        let operation   = BlockOperation {
            // Do something
        }

        task.expirationHandler = {
            // After all operations are cancelled, the completion block below is called to set the task to complete.
            queue.cancelAllOperations()
            self.scheduleNextRefresh()
        }

        operation.completionBlock = {
            task.setTaskCompleted(success: operation.isCancelled)
            self.scheduleNextRefresh()
        }

        queue.addOperation(operation)
    }
}

标签: iosbackground

解决方案


推荐阅读