AVAudioSession setCategory Swift 4.2 iOS 12 - Play Sound on Silent

Nitesh picture Nitesh · Jun 24, 2018 · Viewed 37.8k times · Source

To play sound even on Silent mode I use to use below method. But how it's not working.

// Works on Swift 3  
do {
    try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
} catch {
    print(error)
}

How to get it work in 4.2 / iOS 12?

In newer version we need to set mode and options.

try AVAudioSession.sharedInstance().setCategory(
    <#T##category:AVAudioSession.Category##AVAudioSession.Category#>,
    mode: <#T##AVAudioSession.Mode#>, 
    options: <#T##AVAudioSession.CategoryOptions#>)`

Answer

Rhythmic Fistman picture Rhythmic Fistman · Jun 25, 2018

Her der Töne's comment shows you the new syntax, but you also need to activate the audio session after setCategory:

do {
    try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
    try AVAudioSession.sharedInstance().setActive(true)
} catch {
    print(error)
}