What happens to an iPhone app when iPhone goes into stand-by mode?

后端 未结 6 827
忘掉有多难
忘掉有多难 2020-12-02 07:21

My app uses NSTimer and it appears that NSTimer doesn\'t fire when the iPhone goes into the stand-by mode (either by pressing the hardware button or by the idle timer).

6条回答
  •  时光说笑
    2020-12-02 07:52

    I was faced with this issue recently in an app I am working on that uses several timers and plays some audio prompts and made two relatively simple changes:

    1. In the AppDelegate I implemented the following methods and there mere presence allows the app to continue when the screen is locked

      // this receives the notification when the device is locked
      - (void)applicationWillResignActive:(UIApplication *)application
      { 
      }
      
      // this receives the notification that the application is about to become active again
      - (void)applicationWillBecomeActive:(NSNotification *)aNotification
      {
      }
      

      references: UIApplicationDelegate Protocol Reference & NSApplication Class Reference in the API doc (accessible via Xcode, just search for applicationWillBecomeActive).

    2. Made the main viewcontroller class an AVAudioPlayerDelegate and used this code from Apple's "AddMusic" sample to make the audio alerts the app played mix nicely into the iPod audio etc...

      I just dropped this code into a method that is called during viewDidLoad. If this interests you, you fall into the "who should read this doc" category for this: Audio Session Programming Guide

      // Registers this class as the delegate of the audio session.
      [[AVAudioSession sharedInstance] setDelegate: self];
      
      // The AmbientSound category allows application audio to mix with Media Player
      // audio. The category also indicates that application audio should stop playing 
      // if the Ring/Siilent switch is set to "silent" or the screen locks.
      [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryAmbient error: nil];
      
      // Activates the audio session.
      NSError *activationError = nil;
      [[AVAudioSession sharedInstance] setActive: YES error: &activationError];
      

提交回复
热议问题