启用接近传感器时,我无法让设备使用后视摄像头拍摄图像。我不想显示相机预览,只希望设备拍摄照片并将其显示在imageView中。我的接近传感器工作正常,并且启用了接近传感器时,我正在使用imagePicker.takePicture()拍摄图像,但这似乎不起作用。在没有用户输入的情况下以编程方式拍摄照片的方法/功能是什么?

到目前为止,这是我的代码:

class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {

@IBOutlet var imageView: UIImageView!

var imagePicker: UIImagePickerController!

//*The function in question*
func proximityChanged(notification: NSNotification) {
    let device = notification.object as? UIDevice
    if device?.proximityState == true {
        print("\(device) detected!")

最佳答案

如果您在使用UIImagePickerController捕获照片时遇到麻烦,建议您使用AVFoundation

下面是一个工作示例。接近传感器触发照片捕获。

您可以根据需要添加预览。

import UIKit
import AVFoundation

final class CaptureViewController: UIViewController {

    @IBOutlet weak var imageView: UIImageView!

    private static let captureSessionPreset = AVCaptureSessionPresetPhoto
    private var captureSession: AVCaptureSession!
    private var photoOutput: AVCaptureStillImageOutput!
    private var initialized = false

    override func viewDidLoad() {
        super.viewDidLoad()
        initialized = setupCaptureSession()
    }

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        if initialized {
            captureSession.startRunning()
            UIDevice.currentDevice().proximityMonitoringEnabled = true
            NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(proximityStateDidChange), name: UIDeviceProximityStateDidChangeNotification, object: nil)
        }
    }

    override func viewDidDisappear(animated: Bool) {
        super.viewDidDisappear(animated)
        if initialized {
            NSNotificationCenter.defaultCenter().removeObserver(self, name: UIDeviceProximityStateDidChangeNotification, object: nil)
            UIDevice.currentDevice().proximityMonitoringEnabled = false
            captureSession.stopRunning()
        }
    }

    dynamic func proximityStateDidChange(notification: NSNotification) {
        if UIDevice.currentDevice().proximityState {
            captureImage()
        }
    }

    // MARK: - Capture Image

    private func captureImage() {
        if let c = findConnection() {
            photoOutput.captureStillImageAsynchronouslyFromConnection(c) { sampleBuffer, error in
                if let jpeg  = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer),
                   let image = UIImage(data: jpeg)
                {
                    dispatch_async(dispatch_get_main_queue()) { [weak self] in
                        self?.imageView.image = image
                    }
                }
            }
        }
    }

    private func findConnection() -> AVCaptureConnection? {
        for c in photoOutput.connections {
            let c = c as? AVCaptureConnection
            for p in c?.inputPorts ?? [] {
                if p.mediaType == AVMediaTypeVideo {
                    return c
                }
            }
        }
        return nil
    }

    // MARK: - Setup Capture Session

    private func setupCaptureSession() -> Bool {
        captureSession = AVCaptureSession()
        if  captureSession.canSetSessionPreset(CaptureViewController.captureSessionPreset) {
            captureSession.sessionPreset = CaptureViewController.captureSessionPreset
            if setupCaptureSessionInput() && setupCaptureSessionOutput() {
                return true
            }
        }
        return false
    }

    private func setupCaptureSessionInput() -> Bool {
        if let captureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo),
           let captureDeviceInput = try? AVCaptureDeviceInput.init(device: captureDevice)
        {
            if  captureSession.canAddInput(captureDeviceInput) {
                captureSession.addInput(captureDeviceInput)
                return true
            }
        }
        return false
    }

    private func setupCaptureSessionOutput() -> Bool {
        photoOutput = AVCaptureStillImageOutput()
        photoOutput.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]
        if  captureSession.canAddOutput(photoOutput) {
            captureSession.addOutput(photoOutput)
            return true
        }
        return false
    }

}

10-08 18:51