7

I want to implement a volume shutter in my camera app. When the user presses the volume button, I should get an event to take a photo.

I'm looking for an implementation that meets the following requirements:

  • It should work even if the volume is currently at the maximum, and the user presses the volume up button.
  • There should be no on-screen UI showing that the volume changed.
  • There should be no known cases of Apple rejecting an app that used this technique.

Other questions and answers exist on this topic, but for older versions of iOS, so I wanted to find one that works on iOS 11.

Camera apps like ProCamera, ProCam and Camera+ have the volume shutter that satisfies all these conditions, so it's clearly possible.

7
  • fredandrandall.com/blog/2011/11/18/… Commented Apr 8, 2017 at 17:37
  • What have you tried so far? Show us some code. Commented Apr 8, 2017 at 17:40
  • @backslash-f I wasn't sure what technique to try, since the one(s) I researched all suffered from the above flaws. Before a lot of trial and error, I wanted to see if there's a better solution that has already been found. Commented Apr 9, 2017 at 1:56
  • @ColdSteel Other stack overflow answers point out that many volume shutter techniques that worked five years back no longer work on modern iOS versions. Commented Apr 9, 2017 at 2:19
  • 1
    No one can guarantee your third condition! :)
    – matt
    Commented Apr 11, 2017 at 4:27

2 Answers 2

10
+100

So here is the code that will meet all your requirements – I'm not sure whether or not Apple will approve this though.
I've pulled all this code from questions/answers here on StackOverflow.

Tested with iOS 10.2 in Xcode 8.3.1

You need to use the AVFoundation and MediaPlayer frameworks for this to work.

import UIKit
import AVFoundation
import MediaPlayer

class ViewController: UIViewController {

    //keeps track of the initial volume the user had set when entering the app
    //used to reset the volume when he exits the app
    var volume: Float = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        let audioSession = AVAudioSession.sharedInstance()
        volume = audioSession.outputVolume-0.1 //if the user is at 1 (full volume)
        try! audioSession.setActive(true)
        audioSession.addObserver(self, forKeyPath: "outputVolume", options: NSKeyValueObservingOptions.new, context: nil)
        //prevents the volume hud from showing up
        let volView = MPVolumeView(frame: .zero)
        view.addSubview(volView)
    }

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        //when the user changes the volume,
        //prevent the output volume from changing by setting it to the default volume we specified,
        //so that we can continue pressing the buttons for ever
        (MPVolumeView().subviews.filter{NSStringFromClass($0.classForCoder) == "MPVolumeSlider"}.first as? UISlider)?.setValue(volume, animated: false)

        //implement your photo-capturing function here
        print("volume changed")
    }
}

Update

If you want to make sure your code is still working after the user exits the app, use the AppDelegate to install the observer when the app becomes active, like this:

AppDelegate

import UIKit
import AVFoundation
import MediaPlayer

var volume: Float = 0.5

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    let audioSession = AVAudioSession.sharedInstance()

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        return true
    }

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        (MPVolumeView().subviews.filter{NSStringFromClass($0.classForCoder) == "MPVolumeSlider"}.first as? UISlider)?.setValue(volume, animated: false)

        NotificationCenter.default.removeObserver(self)
        NotificationCenter.default.post(Notification(name: Notification.Name(rawValue: "volumeChanged")))
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        volume = audioSession.outputVolume
        if volume == 0 { volume += 0.1 } else if volume == 1 { volume -= 0.1 }
        try! audioSession.setActive(true)
        audioSession.addObserver(self, forKeyPath: "outputVolume", options: NSKeyValueObservingOptions.new, context: nil)
    }

    func applicationWillResignActive(_ application: UIApplication) {
        audioSession.removeObserver(self, forKeyPath: "outputVolume")
    }
}

ViewController

import UIKit
import AVFoundation
import MediaPlayer

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        NotificationCenter.default.addObserver(self, selector: #selector(self.volumeChanged), name: Notification.Name(rawValue: "volumeChanged"), object: nil)
        //prevents the volume hud from showing up
        let volView = MPVolumeView(frame: .zero)
        view.addSubview(volView)
    }

    func volumeChanged() {
        print("volume changed")
    }
}
16
  • Thanks. When I switch to another app and back, it no longer works — adjusts the ringer volume. Commented Apr 12, 2017 at 14:37
  • 1
    Keep in mind, though, that this is not a service website. You can't expect people to give complete solutions without even trying anything yourself. The code I've provided is a decent basic solution to your problem which you should start tweaking to fully meet your requirements.
    – LinusG.
    Commented Apr 12, 2017 at 14:39
  • I wanted to check if someone already found an answer that gets all the edge cases right before spending time figuring it out again, which I often do, BTW. If you have only a partial solution, that's fine, and I appreciate what you've given me. My comment will also be useful to other people seeing your answer. I'll award you the bounty if no better answer comes along by the time it expires. Commented Apr 12, 2017 at 14:45
  • So, with about 5 minutes of extra coding, I found the solution to the issue you named in your comment. See my updated answer.
    – LinusG.
    Commented Apr 12, 2017 at 15:06
  • You might want to handle the issue that when the user hits the volume buttons, the press is detected twice, so implement some sort of counter for that.
    – LinusG.
    Commented Apr 12, 2017 at 15:07
1

As per Apple's App Store Review Guidelines, this would be explicit grounds for rejection.

2.5.9 Apps that alter the functions of standard switches, such as the Volume Up/Down and Ring/Silent switches, or other native user interface elements or behaviors will be rejected.

Source: Is it possible to disable volume buttons in iOS apps?

2
  • but how snapchat is doing it then? have any idea?
    – Ahmad
    Commented May 18, 2021 at 17:51
  • Thanks for the relevant primary source. Maybe it's considered a legit, expectable function as Apples Camera App does it likewise and so not "altering" when used to take a photo. Commented Aug 23, 2021 at 8:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.