beginBackgroundTaskWithExpirationHandler永远不会被调用

时间:2012-07-23 17:52:25

标签: iphone objective-c ios background-process uiapplication

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

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

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

ffwButtonPressed调用一些不同的方法来改变音轨。完成后......

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

修改声明

UIBackgroundTaskIdentifier bgTask;

编辑:在ViewDidLoad

bgTask = 0;

7 个答案:

答案 0 :(得分:29)

你实际上误解了这个功能 -(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];

以下是documentation

的链接

答案 1 :(得分:2)

我最终根本不需要beginBackgroundTaskWithExpirationHandler。这条线解决了我的问题...

[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];  

答案 2 :(得分:0)

您的应用是否有权在后台作为音频应用运行? (需要在Info.plist中放置正确的模式)

请参阅Apple's docs

答案 3 :(得分:0)

beginBackgroundTaskWithExpirationHandler处理程序仅在计时器runout值时调用,这是一个相当大的值。 Tomsum上面提到的真正任务不应该是块的一部分。还记得调用endBackgroundTask:在结束时如果backGroundTaskID!= UIBackgroundTaskInvalid并且只需要在块中完成设置回任务变量= UIBackgroundTaskInvalid

答案 4 :(得分:0)

快速版本:

    var backgroundTask: UIBackgroundTaskIdentifier? = 0
    backgroundTask = UIApplication.shared.beginBackgroundTask(withName: "backgroundTask", expirationHandler: {() -> Void in
        backgroundTask = UIBackgroundTaskInvalid
    })

    // Perform actions in background
    YOUR_CODE_GOES_HERE (e.g. fetch requests, etc.)

    UIApplication.shared.endBackgroundTask(backgroundTask!)

答案 5 :(得分:0)

可能会有一些修改,我们应该在过期处理程序中添加endBackgroundTask:

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

[self ffwButtonPressed:ffwButton];
NSLog(@"beginBG called");
[app endBackgroundTask:bgTask];

答案 6 :(得分:-1)

这是你的全部代码吗?可能bgTask变量未初始化,您需要在分配之前声明bgTask。试试这个 -

UIBackgroundTaskIdentifier bgTask = nil;