Search code examples
iosswiftalarm

Play Alarm in silent mode in swift


if i am on background audio then developer.apple.com send to me mail

Your app declares support for audio in the UIBackgroundModes key in your Info.plist, but we were unable to play any audible content when the app was running in the background.

Next Steps

The audio key is intended for use by apps that provide audible content to the user while in the background, such as music player or streaming audio apps. Please revise your app to provide audible content to the user while the app is in the background or remove the "audio" setting from the UIBackgroundModes key.

Code :-

let appDelegate = UIApplication.shared.delegate as! AppDelegate
if soundPath == "" {
   appDelegate.playSound()
}else {
   appDelegate.playSoundWithPath(notificationSoundPath: soundPath)
}

Play Sound():-

func playSound() {
  let url = Bundle.main.url(forResource: "loud_alarm", withExtension: "caf")!
  do{
      player = try AVAudioPlayer(contentsOf: url)
      guard let player = player else {return}
      player.prepareToPlay()
      player.play()
    } catch _ as NSError {

    }
}

how to solve this problem


Solution

  • Add below code before you play audio:

    do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
     }
     catch {
        // catch error
     }