UIImagePickerController--当用户将摄像头从前面换到后面时,获得通知,反之亦然。

问题描述 投票:0回答:1

基本上,我正在寻找的是一个UIImagePickerContoller功能,当用户从后置摄像头切换到前置摄像头时(反之亦然),它会通知我。我阅读了苹果的文档,但没有找到类似的东西。

例如,在 这个问题 小伙子添加了一个自定义按钮来切换前后摄像头。这是否是唯一的选择?

swift uiimagepickercontroller
1个回答
-1
投票

对于那些面临同样问题的人,我找到了以下内容 正确答案

这是它的Swift 5翻译。

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)
        }
}
© www.soinside.com 2019 - 2024. All rights reserved.