14

I am making an application where audio will play in the background. In the following code, bgTask is undeclared. What kind of object should bgTask be?

- (void)applicationDidEnterBackground:(UIApplication *)application 
{
    UIApplication  *app = [UIApplication sharedApplication];
    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{ 
        [app endBackgroundTask:bgTask]; 
        bgTask = UIBackgroundTaskInvalid;
    }];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{});

    [app endBackgroundTask:bgTask]; 
    bgTask = UIBackgroundTaskInvalid;
}
Community
  • 1
  • 1
sidhu
  • 181
  • 1
  • 2
  • 8

3 Answers3

17

You need to declare bgTask before you assign:

UIBackgroundTaskIdentifier bgTask = 0;
Dev
  • 7,027
  • 6
  • 37
  • 65
willcodejavaforfood
  • 43,223
  • 17
  • 81
  • 111
  • 10
    thanks. I want to spank myself every time I read one of these vague docs written by Apple (~90% of their docs). They should hire people who know how to write docs. – Duck Aug 25 '11 at 17:00
  • 25
    You want to spank yourself..? – Andy May 03 '12 at 13:24
  • @willcodejavaforfood I have tried this code with a timer but timer stops after round 10 minutes how can I continue it in a long time – Johnykutty Jun 05 '12 at 09:26
  • 12
    Just to clarify, it should be `UIBackgroundTaskIdentifier bgTask = 0;` since it is a `NSUInteger`. – Alexandre OS Aug 23 '12 at 12:35
10

I cannot comment on previous answers, however to initialize UIBackgroundTaskIdentifier you should not set it to nil or 0. You should set it to:

UIBackgroundTaskInvalid

In the documentation UIBackgroundTaskInvalid says it should be used to initialize variables or to check for errors.

Bontarest
  • 171
  • 1
  • 5
2

You are using the bgTask in the block so you have to declare it like this..

__block UIBackgroundTaskIdentifier bgTask = 0;

__block will allow this variable to use in the block method. And its have double underscore.

Dilip Manek
  • 9,095
  • 5
  • 44
  • 56