Custom sounds in remote notifications iOS 10, swif

2019-07-26 18:40发布

问题:

I've a big problem with a custom sounds in remote notifications.

This is my scenario:

I've two types of notifications each one with a custom sound. The sound, plays like a charm, when my app is inactive or in background, and the OS shows the notification in notification center banner-alert.

When the notification is received in foreground state, I process the notification, extract the aps sound element and I play the sound via AVAudioPlayer:

func playSound(_ sound: String) {
    myLog("Let's play sound \(sound)")

    // Plays new sound file
    DispatchQueue.main.async  {
        // Stops last player if playing
        if (self.soundPlayer != nil) {
            if (self.soundPlayer.isPlaying) {
                self.soundPlayer.stop()
            }
        }
        do {
            let path = Bundle.main.path(forResource: sound, ofType:nil)!
            let url = URL(fileURLWithPath: path)
            self.soundPlayer = try AVAudioPlayer(contentsOf: url)
            self.soundPlayer.delegate = self
            if (self.soundPlayer.prepareToPlay()) {
                self.soundPlayer.play()
            }
        } catch let error  {
            myLog("Error playing .caf file: \(error)")
        }
    }

}

And here start the problem. If the app returns to background - inactive when my player code is executed the OS alert in notification center never plays again the custom sounds.

Summarizing:

  • App inactive - background it receives notification -> Custom sounds plays ok.

  • App foreground it receives notification -> code plays sound via playSound function then if app receives other notification in background-inactive state OS plays default notification sound.

Thanks in advance.

回答1:

Problem auto-solved. Deleting app, sound return to normal behaviour.