Using iOS 12, I am observing AVSystemController_SystemVolumeDidChangeNotification
to detect volume presses to capture images:
let volumeView = MPVolumeView(frame: CGRect(x: 0, y: -40, width: 0, height: 0)) // override volume view
view.addSubview(volumeView)
NotificationCenter.default.addObserver(self, selector: #selector(captureImage), name: Notification.Name(rawValue: "AVSystemController_SystemVolumeDidChangeNotification"), object: nil)
However, I've noticed that the notification also fires, at least on an iPhone XS and XS Max, when the lock button (on the right side of the device) is pressed.
Tried searching around and haven't seen anyone mentioning this issue or much discussion of this notification. Other similar attempts to listen to the volume buttons presses use AVAudionSessions / KVO, but I found that whenever I used that the observer did not get called when the volume was already at max/min. This AVSystemController_SystemVolumeDidChangeNotification
seems to work just fine, except for this strange lock button issue. Don't see how, from the name of the notification, why it would respond to the lock button being pressed.
When the lock button is pressed I get the following messages in the console:
[avas] AVAudioSessionPortImpl.mm:56:ValidateRequiredFields: Unknown selected data source for Port Speaker (type: Speaker) // this appears four times
+[CATransaction synchronize] called within transaction // this appears twice
These logs do not appear when the volume button is pressed.
Note also I don't plan to submit the App Store, so I am not concerned about whether Apple rejects this app on the basis of using this possibly private notification.
If instead of AVSystemController_SystemVolumeDidChangeNotification
I create an AVAudioSession
and observe outputVolume
like so:
let audioSession = AVAudioSession()
try? audioSession.setActive(true)
audioSession.addObserver(self, forKeyPath: "outputVolume", options: NSKeyValueObservingOptions.new, context: nil)
… then it isn't hit when the device locks, but I'm still seeing the "AVAudioSessionPortImpl.mm unknown selected data source for Port Speaker" console errors. But then when the volume is muted it doesn't receive presses anymore. I guess what I'd need to do is manually change the volume so it doesn't hit the min or max?
Thank you