美文网首页selector
iOS Background Task 遇到的问题

iOS Background Task 遇到的问题

作者: UILabelkell | 来源:发表于2020-06-30 16:38 被阅读0次

    第一种情况

    beginBackgroundTaskWithExpirationHandler调用endBackgroundTask但没有结束进程

    即使应用程序在后台运行,我也有一些长时间运行的进程.我正在调用应用程序的beginBackgroundTaskWithExpirationHandler:方法,并在expirationBlock中调用应用程序的endBackgroundTask.
    这是实施:

    __block UIBackgroundTaskIdentifier task = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        [[UIApplication sharedApplication] endBackgroundTask:task];
        task = UIBackgroundTaskInvalid;
    }];
    dispatch_queue_t queue = dispatch_queue_create("com.test.test1234", DISPATCH_QUEUE_SERIAL);
    dispatch_async(queue, ^{
        // My Task goes here
    });
    

    在某些情况下,我的串行队列有更多的任务要执行,这些任务无法在系统提供的时间内完成.所以到期块将执行,因为我结束了UIBackgroundTaskIdentifier但没有停止调度过程(我甚至无法取消调度).

    如果使用我当前的实现,如果我调用endBackgroundTask:在expirationHandler块中,我的调度队列的任务没有完成?我的应用将被终止或暂停?
    下面是一些场景,您需要在使用beginBackgroundTaskWithExpirationHandler时处理,否则您的应用将终止.

    场景1:您的应用程序正在Foreground中运行.你开始
    beginBackgroundTaskWithExpirationHandler然后进入后台模式.你的应用程序保持活力很久.

    场景2:您的应用程序正在Foreground中运行.你开始beginBackgroundTaskWithExpirationHandler然后进入后台模式.然后回到Foreground模式并且你没有调用endBackgroundTask然后你的应用程序仍然执行后台队列,因此它将在接下来的3分钟内扩展该过程(在IOS 7介绍之后.在IOS 7之前,过程执行时间是10分钟).所以你必须要取消后台队列和任务从后台队列中出来并进入前台队列.

    以下是向您展示的代码.什么是处理后台进程的最佳方式.

    步骤1:将__block UIBackgroundTaskIdentifier bgTask声明为全局变量.

    第2步:在applicationDidEnterBackground中添加以下代码.

    - (void)applicationDidEnterBackground:(UIApplication *)application {
    
             bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
             bgTask = UIBackgroundTaskInvalid;
              }];
    
    }
    

    第3步:一旦应用程序进入前台模式,停止后台任务处理程序

    - (void)applicationWillEnterForeground:(UIApplication *)application {
      // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    
      [[UIApplication sharedApplication] endBackgroundTask:bgTask];
    
    }
    

    Background Task 这种方式,就是系统提供了 beginBackgroundTaskWithExpirationHandler 方法来延长后台执行时间,可以解决你退后台后还需要一些时间去处理一些任务的诉求。但在使用时碰到一些问题:

    第二种情况

    如果是debug调试状态,你会发现程序退到后台,任务会一直在执行。
    测试后台执行时间时,不能是调试状态。必须断开xcode
    beginBackgroundTaskWithExpirationHandler与endBackgroundTask是成对出现的。如果不成对出现,几秒钟后 app会被杀掉。
    正确写法:yourTask应该放在

    beginBackgroundTaskWithExpirationHandler前调用,而不是block块
    [self yourTaskWithApplication:application];
    self.backgroundTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^(void) {
    [application endBackgroundTask:self.backgroundTaskIdentifier];
    self.backgroundTaskIdentifier = UIBackgroundTaskInvalid;
    }];
    

    我们可以借助 控制台 来判断app是否还在执行,日志是否还在打印。

    相关文章

      网友评论

        本文标题:iOS Background Task 遇到的问题

        本文链接:https://www.haomeiwen.com/subject/fyvxqktx.html