7

在后台实现定时器如下并使用 XCode 4.5.2

UIDevice *device = [UIDevice currentDevice];
    BOOL backgroundSupported = NO;
    if ([device respondsToSelector:@selector(isMultitaskingSupported)]) {
        backgroundSupported = YES;
    }

    if (backgroundSupported) 
    {
        bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{ 
            [[UIApplication sharedApplication] endBackgroundTask:bgTask];
        }];

      /*timer code goes here*/
    }

我的应用程序在后台运行,我在 AppDelegate 的方法中有上述代码,applicationDidEnterBackground并在 gdb 中获得以下消息

Can't endBackgroundTask:不存在标识符为 4 的后台任务,或者它可能已经结束。中断 UIApplicationEndBackgroundTaskError() 进行调试。

我知道这个问题类似于Can't endBackgroundTask但没有答案或建议。有任何想法吗 ?

4

1 回答 1

6

Make sure you are declaring bgTask like so: UIBackgroundTaskIdentifier bgTask = UIBackgroundTaskInvalid;

I think you may have bgTask declared as an int or NSNumber.

于 2013-07-13T22:02:22.663 回答