beginBackgroundTaskWithExpirationHandler永远不会被调用

mno*_*rt9 8 iphone objective-c background-process uiapplication ios

我有一个在后台播放音频的应用程序.我正试图beginBackgroundTaskWithExpirationHandler在当前曲目结束时跳到下一首曲目.

以下是播放状态更改时调用的代码.它永远不会记录"beginBG called",即使同一方法中的其他代码在后台成功实现.

UIApplication *app = [UIApplication sharedApplication];
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
    [self ffwButtonPressed:ffwButton];
    NSLog(@"beginBG called");
    [app endBackgroundTask:bgTask];
    bgTask = UIBackgroundTaskInvalid;
}];
Run Code Online (Sandbox Code Playgroud)

ffwButtonPressed调用一些不同的方法来改变轨道.什么时候完成......

UIApplication *app = [UIApplication sharedApplication];
    if (bgTask != UIBackgroundTaskInvalid) {
        [app endBackgroundTask:bgTask]; 
        bgTask = UIBackgroundTaskInvalid;
        NSLog(@"end bgTask");
Run Code Online (Sandbox Code Playgroud)

编辑:声明

UIBackgroundTaskIdentifier bgTask;
Run Code Online (Sandbox Code Playgroud)

编辑:在ViewDidLoad中

bgTask = 0;
Run Code Online (Sandbox Code Playgroud)

Tom*_*usm 30

你实际上是误解了这个功能 -(UIBackgroundTaskIdentifier)beginBackgroundTaskWithExpirationHandler:(void (^)(void))handler

名为"handler"的块参数是后台任务到期时(10分钟)将发生的事情.

要使代码运行,您需要将代码放在过期处理程序之外:

UIApplication *app = [UIApplication sharedApplication];
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
    bgTask = UIBackgroundTaskInvalid;
};

[self ffwButtonPressed:ffwButton];
NSLog(@"beginBG called");
[app endBackgroundTask:bgTask];
Run Code Online (Sandbox Code Playgroud)

这是文档的链接