0

Coincidentally, I encountered some strange behavior from my source code while developing an app:

I have started an interval that calls a function to output the set volume of the device.

When testing the code on a real device (iPhone X), I noticed that the "value of the volume does not seem to change" when I press one of the volume buttons.

This was the code I was using:

Timer.scheduledTimer(
            timeInterval: 0.5,
            target: self,
            selector: #selector(self.getSystemVolume),
            userInfo: nil,
            repeats: true)

@objc func getSystemVolume() {
    let outputVolume = AVAudioSession.sharedInstance().outputVolume
    print(outputVolume)
}

Note: I'm not sure if this is a bug or not - could be!

However: Does anyone now how to fix behavior? Any help would be very appreciated :)

1 Answers1

0

Looks like I've found a working solution on my own:

I've added those lines:

let volumeView = MPVolumeView()
    volumeView.setNeedsLayout()

I got no idea why these lines cause the code to work, but however - now it's working.

@objc func getSystemVolume() {
    let volumeView = MPVolumeView()
    volumeView.setNeedsLayout()
    let outputVolume = AVAudioSession.sharedInstance().outputVolume
    print(outputVolume)
}  

I really hope somebody could add a comment why these lines fix the code. :)