was created over 30 seconds ago 警告

具体问题是这样的:
进行了一个后台播放音频的处理,代码如下:

- (void)sceneDidEnterBackground:(UIScene *)scene {
    UIApplication *app = [UIApplication sharedApplication];
    __block UIBackgroundTaskIdentifier bgTask;
    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (bgTask != UIBackgroundTaskInvalid){
                bgTask = UIBackgroundTaskInvalid;
            }
        });

    }];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (bgTask != UIBackgroundTaskInvalid){
                bgTask = UIBackgroundTaskInvalid;
            }
        });
    });
}

这样就可以实现APP进入后台后依然可以播放音频文件而不会被暂停,但是在进入后台后,发现30秒后log打印如下信息:

... was created over 30 seconds ago. In applications running in the background, this creates a risk of termination. Remember to call UIApplication.endBackgroundTask(_:) for your task in a timely manner to avoid this.

意思就是我在上面进行了beginBackgroundTaskWithExpirationHandler方法,需要在必要的时候调用endBackgroundTask方法,所以修改如下:

//在头部定义全局变量
#import "SceneDelegate.h"
@interface SceneDelegate (){
    __block UIBackgroundTaskIdentifier backgroundUpdateTask;
}
@end


- (void)sceneDidEnterBackground:(UIScene *)scene {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        [self beginBackgroundUpdateTask];
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            dispatch_async(dispatch_get_main_queue(), ^{
                if (self->backgroundUpdateTask != UIBackgroundTaskInvalid){
                    self->backgroundUpdateTask = UIBackgroundTaskInvalid;
                }
            });
        });
        
        [self endBackgroundUpdateTask];
    });

  
    
}
- (void) beginBackgroundUpdateTask
{
    backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (self->backgroundUpdateTask != UIBackgroundTaskInvalid){
                self->backgroundUpdateTask = UIBackgroundTaskInvalid;
            }
        });
        
        [self endBackgroundUpdateTask];
    }];
}


- (void) endBackgroundUpdateTask
{
    [[UIApplication sharedApplication] endBackgroundTask: backgroundUpdateTask];
    backgroundUpdateTask = UIBackgroundTaskInvalid;
}


再次运行,警告解决.

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容