I would like to use volume up / volume down to shoot a picture inside my app (coded in Swift 3.2), in the same way iOS built in Camera app does.
Is there an easy way of doing that? It would be great if it was code only (no storyboards involved)
Thank you!
Asked
Active
Viewed 1,201 times
1

Dimitre L
- 11
- 2
-
Possible duplicate of [Detect volume button press](https://stackoverflow.com/questions/28471481/detect-volume-button-press) – shallowThought Jan 14 '18 at 19:58
1 Answers
2
There is no straightforward API's available for now. But below workaround would be working for your condition.
- Listen to
AVAudioSession
keypathoutputVolume
and when there is new value you can capture a photo.
import AVFoundation
var audioSession = AVAudioSession()
try audioSession.setActive(true)
audioSession.addObserver(self, forKeyPath: "outputVolume", options: NSKeyValueObservingOptions.new, context: nil)
func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
if keyPath == "outputVolume"{
// capture photo here.
}
}

Bluewings
- 3,438
- 3
- 18
- 31
-
1FYI. For Swift 5, the correct function signature is: `override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?)` – P. Ent Sep 17 '21 at 18:41