title: AVAudioPlayer play file in Background
body: <p>I am developing music app in which app should be run in background.</p>
  
  <p>That is when user select file to play and he pressed home button 
  then file should continue to play in background.</p>
  
  <p>I am using AVAudioPlayer.</p>
  
  <p>I tried this: </p>
  
  <pre><code>**AppDelegate.m**
  
  
  - (void)applicationDidEnterBackground:(UIApplication *)application {
  UIApplication* app = [UIApplication sharedApplication];
  
  NSAssert(self-&gt;bgTask == UIBackgroundTaskInvalid, nil);
  
  bgTask = [app beginBackgroundTaskWithExpirationHandler: ^{
      dispatch_async(dispatch_get_main_queue(), ^{
          [app endBackgroundTask:self-&gt;bgTask];
          self-&gt;bgTask = UIBackgroundTaskInvalid;
      });
  }];
  
  dispatch_async(dispatch_get_main_queue(), ^{
      self-&gt;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;
      }
  }
  }
  </code></pre>