ios - Swift 3 照片拍摄

标签 ios swift swift3

我正在使用这段代码:

func capturePhoto(blockCompletion: @escaping blockCompletionCapturePhoto) {
    guard let connectionVideo  = self.stillCameraOutput.connection(withMediaType: AVMediaTypeVideo) else {
        blockCompletion(nil, nil)
        return
    }

    connectionVideo.videoOrientation = AVCaptureVideoOrientation.orientationFromUIDeviceOrientation(orientation: UIDevice.current.orientation)

    self.stillCameraOutput.captureStillImageAsynchronouslyFromConnection(connectionVideo) { (sampleBuffer: CMSampleBuffer!, err: NSError!) -> Void in
        if let err = err {
            blockCompletion(image: nil, error: err)
        }
        else {
            if let sampleBuffer = sampleBuffer, let dataImage = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer) {
                let image = UIImage(data: dataImage)
                blockCompletion(image: image, error: nil)
            }
            else {
                blockCompletion(image: nil, error: nil)
            }
        }
    }
}

它在 Swift 2.0 中工作正常,但在转换后它不再工作了。 这一行:

self.stillCameraOutput.captureStillImageAsynchronouslyFromConnection(connectionVideo) { (sampleBuffer: CMSampleBuffer!, err: NSError!) -> Void in 

给我以下错误:

Cannot convert value of type '(CMSampleBuffer!, NSError!) -> Void' to expected argument type '((CMSampleBuffer?, Error?) -> Void)!'

我已经尝试了一些事情,但无法解决。 希望有人能帮助我。

最佳答案

什么错误

Cannot convert value of type '(CMSampleBuffer!, NSError!) -> Void' to expected argument type '((CMSampleBuffer?, Error?) -> Void)!'

基本上是说您的参数类型错误 ((CMSampleBuffer!, NSError!) -> Void) 而它应该是类型 ((CMSampleBuffer?, Error? ) -> 无效)!.

为此,请尝试使用此代码,它应该会自动使您的 block 符合正确的类型:

self.stillCameraOutput.captureStillImageAsynchronouslyFromConnection(connectionVideo) { sampleBuffer, error in
    //do stuff with your sample buffer, don't forget to handle errors
}

它看起来像一个奇怪的类型,但我认为这是 Apple 在将这段代码从 ObjC 迁移到 Swift 1、Swift 2 再到 Swift 3 时犯的一个小错误。
我还没有测试过这段代码,但我认为它应该可以工作,如果真的可以,请告诉我!

关于ios - Swift 3 照片拍摄,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39492339/

相关文章:

ios - Swift countElements() 在计数标志 emoji 时返回不正确的值

ios - 如何让 react-native 在 Mac OS X El Capitan 中使用主机文件?

ios - 来自NSAttributedString的UITextField下划线只有1个像素高吗?

ios - 如何在 iOS 中为自定义属性设置动画

xcode - 如何从我的 XCode Assets 目录中获取 CGImage

swift - 实例方法 'match(match:player:didChangeState:)'几乎匹配协议(protocol) 'match(_:player:didChange:)'的可选要求 'GKMatchDelegate'

ios - Swift iOS 声音内存泄漏?

ios - 如何更改属性数组的字体大小(swift,ios)

ios - 快速禁用 UITextField 中的闪烁光标?

ios - 沿 X 轴拖动 SceneKit 节点同时保持速度?雨燕3