【问题标题】:UIImagePickerController - get notification when user changes camera from front to rear and vice versa [duplicate]UIImagePickerController - 当用户从前到后更改相机时收到通知,反之亦然[重复]
【发布时间】:2020-05-04 10:34:08
【问题描述】:

基本上我正在寻找的是一个 UIImagePickerContoller 函数,它会在用户将相机从后到前切换时通知我(反之亦然)。我正在阅读 Apple 的文档,但找不到类似的东西。

例如在this question guy 添加了一个自定义按钮来切换前后摄像头。会是唯一的选择吗?

【问题讨论】:

  • @jawadAli 谢谢,但这并不是我真正要求的。因为第一个它不是一个函数,第二个它不在 Swift 中,第三个它并没有真正做我想要的

标签: swift uiimagepickercontroller


【解决方案1】:

对于那些遇到同样问题的人,我找到了the correct answer

这是它的 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)
        }
}

【讨论】:

    猜你喜欢
    • 2012-06-28
    • 2023-03-04
    • 2020-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多