UIButton捕获无响应的图像

时间:2017-08-06 17:12:30

标签: ios swift

我是iOS开发的新手,我正在尝试按照以下教程学习如何捕获图像,然后将它们保存在服务器上以实现我的目的:

https://medium.com/@rizwanm/swift-camera-part-2-c6de440a9404

教程非常棒,我只是初始化相机并尝试拍摄图像(不进行QR部分)。 不幸的是,当我点击“捕获”时按钮,图像没有被拍摄或保存在我的画廊中,我无法理解为什么。我使用Xcode 8.3,我在iPhone上运行iOS 10.3。

我已将按钮与视图控制器连接,并在函数onTapTakePhoto中调用它,如下面的代码所示。请告知为什么会发生这种情况。

import UIKit
import AVFoundation

class ViewController: UIViewController {
    @IBOutlet weak var previewView: UIView!
    @IBOutlet weak var CaptureButton: UIButton!

    //helps transfer data between one or more input device like camera
    var captureSession: AVCaptureSession?
    //instance variable
    var capturePhotoOutput: AVCapturePhotoOutput? //capturePhotoOutput will help us snap a live photo

    //helps render the camera view finder in ViewController
    var videoPreviewLayer: AVCaptureVideoPreviewLayer?

    override func viewDidLoad() {
        super.viewDidLoad()

        CaptureButton.layer.cornerRadius = CaptureButton.frame.size.width / 2
        CaptureButton.clipsToBounds = true

        //set up camera here
        let captureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)

        // get an instance of the AVCAptureDevicenput
        // serves as a middle man to attach input device to capture device
        // chance the input device unavailable so wrap in do catch

        do {
            // Get an instance of the AVCaptureDeviceInput class using the previous deivce object
             let input = try AVCaptureDeviceInput(device: captureDevice)
            // Initialize the captureSession object
            captureSession = AVCaptureSession()

            // Set the input devcie on the capture session
            captureSession?.addInput(input)

            //set up preview view to see live feed
            videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
            videoPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
            videoPreviewLayer?.frame = view.layer.bounds
            previewView.layer.addSublayer(videoPreviewLayer!)

            // finally start the capture session
            captureSession?.startRunning()

            // get an instance of AVCapturePhotoOutput class
            capturePhotoOutput = AVCapturePhotoOutput()
            capturePhotoOutput?.isHighResolutionCaptureEnabled = true
            //set the outut on the capture session
            captureSession?.addOutput(capturePhotoOutput)

        } catch {
            print (error)
            return
        }
    }

    @IBAction func onTapTakePhoto(_ sender: UIButton) {
        // Make sure capturePhotoOutput is valid
        guard let capturePhotoOutput = self.capturePhotoOutput else { return }

        // Get an instance of AVCapturePhotoSettings class
        let photoSettings = AVCapturePhotoSettings()

        // Set photo settings for our need
        photoSettings.isAutoStillImageStabilizationEnabled = true
        photoSettings.isHighResolutionPhotoEnabled = true
        photoSettings.flashMode = .auto

        // Call capturePhoto method by passing our photo settings and a delegate implementing AVCapturePhotoCaptureDelegate
        capturePhotoOutput.capturePhoto(with: photoSettings, delegate: self)
    }
}

// to get the captured image
extension ViewController : AVCapturePhotoCaptureDelegate {
    func capture(_ captureOutput: AVCapturePhotoOutput,
                 didFinishProcessingPhotoSampleBuffer photoSampleBuffer: CMSampleBuffer?,
                 previewPhotoSampleBuffer: CMSampleBuffer?,
                 resolvedSettings: AVCaptureResolvedPhotoSettings,
                 bracketSettings: AVCaptureBracketedStillImageSettings?,
                 error: Error?) {
        // Make sure we get some photo sample buffer
        guard error == nil,
            let photoSampleBuffer = photoSampleBuffer else {
                print("Error capturing photo: \(String(describing: error))")
                return
        }

        // Convert photo same buffer to a jpeg image data by using AVCapturePhotoOutput
        guard let imageData = AVCapturePhotoOutput.jpegPhotoDataRepresentation(forJPEGSampleBuffer: photoSampleBuffer, previewPhotoSampleBuffer: previewPhotoSampleBuffer) else {
            return
        }

        // Initialise an UIImage with our image data
        let capturedImage = UIImage.init(data: imageData , scale: 1.0)
        if let image = capturedImage {
            // Save our captured image to photos album
            UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
        }
    }
}

4 个答案:

答案 0 :(得分:0)

您应检查的一件事是,如果您已在info.plist文件中添加了权限以访问相机。

您必须为密钥

创建键值条目
  

隐私 - 照片库使用说明

(如果您使用的是图库)

  

隐私 - 相机使用说明

使用相机本身。

有关详细信息,请参阅this

如果它不起作用,请将调试器放在按钮的单击操作上并检查代码流。如果在按下按钮后未按下调试器,则按钮操作插座可能存在问题,请尝试重新设置插座操作。

答案 1 :(得分:0)

首先在断点的帮助下,检查代码的哪一部分没有被执行。可能存在与按钮连接相关的一些问题。

OR 试试这个吧 https://www.youtube.com/watch?v=994Hsi1zs6Q

OR 这个在Objective-C中 https://github.com/omergul/LLSimpleCamera

答案 2 :(得分:0)

感谢您的回答:)

问题是与故事板上的操作按钮代码缺少连接。回想起来,感觉就像这样一个愚蠢的错误

答案 3 :(得分:0)

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

        if (info[UIImagePickerControllerOriginalImage] as? UIImage) != nil {
          }
        dismiss(animated: true, completion:
            {
               // write your set image code for UIButton is here.
            })
    }