2

I am developing music app in which app should be run in background.

That is when user select file to play and he pressed home button then file should continue to play in background.

I am using AVAudioPlayer.

I tried this:

**AppDelegate.m**


- (void)applicationDidEnterBackground:(UIApplication *)application {
UIApplication* app = [UIApplication sharedApplication];

NSAssert(self->bgTask == UIBackgroundTaskInvalid, nil);

bgTask = [app beginBackgroundTaskWithExpirationHandler: ^{
    dispatch_async(dispatch_get_main_queue(), ^{
        [app endBackgroundTask:self->bgTask];
        self->bgTask = UIBackgroundTaskInvalid;
    });
}];

dispatch_async(dispatch_get_main_queue(), ^{
    self->bgTask = UIBackgroundTaskInvalid;
});

}

**Player.m**

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

}

-(BOOL)canBecomeFirstResponder{ 
NSLog(@"canBecomeFirstResponder");
return YES; 
} 

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

- (void)remoteControlReceivedWithEvent:(UIEvent*)receivedEvent{

NSLog(@"remoteControlReceivedWithEvent");

if (receivedEvent.type == UIEventTypeRemoteControl){
    switch (receivedEvent.subtype){
        case UIEventSubtypeRemoteControlTogglePlayPause:
            NSLog(@"UIEventSubtypeRemoteControlTogglePlayPause");
            break;
        case UIEventSubtypeRemoteControlPreviousTrack:
            NSLog(@"UIEventSubtypeRemoteControlPreviousTrack");
            break;
        case UIEventSubtypeRemoteControlNextTrack:
            break;
        default:
            break;
    }
}
}
Dilip Lilaramani
  • 1,126
  • 13
  • 28

0 Answers0