Ashish Chauhan
Ashish Chauhan

Reputation: 1376

I have an iPad app that plays audio in background but app icon is not appear with ipod controls

My problem is - when audio is playing in background in my iPad then "my app icon" is not coming. I am using iPodMusicPlayer. For playing audio in background I have write these code..

- (void)viewDidAppear:(BOOL)animated {
      [super viewDidAppear:animated];
      [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
      [self becomeFirstResponder];
}

- (void)viewWillDisappear:(BOOL)animated
{
     [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
     [self resignFirstResponder];
     [super viewWillDisappear:animated];
}

- (BOOL)canBecomeFirstResponder {
        return YES;
}

// The iPod controls will send these events when the app is in the background

- (void) remoteControlReceivedWithEvent: (UIEvent *) receivedEvent {
       if (receivedEvent.type == UIEventTypeRemoteControl) {
           switch (receivedEvent.subtype) {

           case UIEventSubtypeRemoteControlTogglePlayPause:
               [self performSelector:@selector(playPause:)];
               break;

           case UIEventSubtypeRemoteControlPreviousTrack:
            //[self previousSong:nil];
            //[self performSelector:@selector(previousSong:)];
            break;

           case UIEventSubtypeRemoteControlNextTrack:
               //[self performSelector:@selector(nextSong:)];
               break;
          default:
              break;
         }
     }
}

and info.plist I have also set "required background mode"

Upvotes: 1

Views: 636

Answers (1)

Bojan Dimovski
Bojan Dimovski

Reputation: 1216

You will also have to add UIBackgroundModes to your Info.plist and set its value to audio.

Please check the iOS App Programming Guide, specifically the App States and Multitasking section for detailed info on how to execute tasks in background.

[UPDATE]

Also add these two lines to application:didFinishLaunchingWithOptions: in your AppDelegate.m:

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];

And this code when you start playing your audio:

UIBackgroundTaskIdentifier newTaskId = UIBackgroundTaskInvalid;
[_player play];
newTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL];

This should do it. Tested in the simulator, as well as on a device.

Upvotes: 2

Related Questions