How are some alarm apps such as Alarmy able to play a sound on iPhone when the app is in the background and the phone is on vibrate

前端 未结 2 1663
南旧
南旧 2021-02-12 17:34

I am working on app that can alert users for some critical things. I use local notifications to alert the user. On iOS, I find that the notifications will not ring if the phone

2条回答
  •  名媛妹妹
    2021-02-12 18:13

    There are few methods to implement this kind of functionality.For reference I recommend this link.

    For actually playing the sound while the device’s ringer switch is set to vibrate

    First off make sure to include the audio background mode in the capabilities, in order to play audio in the background.

    Then,

    Swift 4

    do {
      try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord, with: [.duckOthers, .defaultToSpeaker])
      try AVAudioSession.sharedInstance().setActive(true)
      UIApplication.shared.beginReceivingRemoteControlEvents()
    } catch {
      NSLog("Audio Session error: \(error)")
    }
    

    Here we set the shared audio session’s category to AVAudioSessionCategoryPlayAndRecord, so that we can play sound, while the device’s ringer switch is set to vibrate.

    The .duckOthers is specified to make other audio quieter, if there’s any mixable audio playing, so that our alarm can be heard. You can leave that out or use another option, if you prefer a different behavior.

    The .defaultToSpeaker is specified, so that the volume would go to the speaker, where it’ll be much louder and should wake up our user with ease.

    beginReceivingRemoteControlEvents makes it so that the app handles the remote control options, like the play/pause buttons on the lock screen, in order to make it easier for our user to mute their alarm, once they wake up.

提交回复
热议问题