Подтвердить что ты не робот

Как сделать снимок с помощью датчика приближения?

У меня возникла проблема с приложением устройства для съемки изображения с помощью камеры заднего вида, когда включен датчик приближения. Я не хочу, чтобы предварительный просмотр камеры отображался, просто хотите, чтобы устройство взяло фотографию и представило ее в 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!")
4b9b3361

Ответ 1

Если у вас возникли проблемы с фотографированием с помощью 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
    }

}