ios - UIButton 捕捉图像没有响应

标签 ios swift

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

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

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

我已将按钮与 View Controller 连接起来,并在函数 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)
        }
    }
}

最佳答案

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

您必须为键创建一个键值条目

Privacy - Photo Library Usage Description

(如果您使用图库)

Privacy - Camera Usage Description

用于使用相机本身。

引用this了解更多详情。

如果不起作用,请在按钮的单击操作上放置调试器并检查代码流程。如果按下按钮后没有命中调试器,则按钮操作 socket 可能有问题,请尝试重新制作 socket 操作。

关于ios - UIButton 捕捉图像没有响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45534554/

相关文章:

ios - 在加载数据之前完成所有异步请求?

ios - 核心数据模型,游戏有输有赢,一个玩家有多局?

ios - UICollectionView.backgroundView 损坏

ios - 居中对齐 UILabel 文本?

iPhone 和 iPad 的 iOS 分辨率

iphone - 以编程方式更改基于 UIWebkit 的应用程序的方向

ios - 将密码管理器集成到 iPhone 应用程序中

swift - 当我创建一个注销的segue时,导航 Controller 突然出现 - Swift

python - 是否有一个函数可以检查字符串中的字符是否是字母表中的字母? ( swift )

swift - 在实时相机预览上应用自定义相机滤镜 - Swift