-1

Basically what I am looking for is a UIImagePickerContoller function that would notify me when user switches camera from rear to front (and vice versa). I was reading through Apple's documentation and couldn't find anything similar.

E.g. in this question guy added a custom button to switch between front and rear camera. Would it be the only option?

Shalugin
  • 1,092
  • 2
  • 10
  • 15

1 Answers1

-1

For those who faced the same problem, I found the correct answer

This is its Swift 5 translation:

var context = 0

override func viewDidLoad() {
   super.viewDidLoad()

//Registering for notifications

   let notificationCenter = NotificationCenter.default
   notificationCenter.addObserver(self, selector: #selector(handleCaptureSessionDidStartRunning(notification:)), name: NSNotification.Name.AVCaptureSessionDidStartRunning, object: nil)
   notificationCenter.addObserver(self, selector: #selector(handleCaptureSessionDidStopRunning(notification:)), name: NSNotification.Name.AVCaptureSessionDidStopRunning, object: nil)
}

@objc func handleCaptureSessionDidStartRunning(notification: NSNotification) {
    guard let session = notification.object as? AVCaptureSession else { return }
    session.addObserver(self, forKeyPath: "inputs", options: [ .old, .new ], context: &context)
}

@objc func handleCaptureSessionDidStopRunning(notification: NSNotification) {
    guard let session = notification.object as? AVCaptureSession else { return }
    session.removeObserver(self, forKeyPath: "inputs")
}

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if context == &self.context {
        if let inputs = change?[NSKeyValueChangeKey.newKey] as? [AnyObject], let captureDevice = (inputs.first as? AVCaptureDeviceInput)?.device {
            switch captureDevice.position {
                case .back:
                    print("Switched to back camera")
                case .front:
                    print("Switched to front camera")
                default:
                    break
                }
            }
        } else {
            super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
        }
}
Shalugin
  • 1,092
  • 2
  • 10
  • 15