具体问题是这样的:
进行了一个后台播放音频的处理,代码如下:
- (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;
}
再次运行,警告解决.