Swift 3 photo capturing

此生再无相见时 提交于 2020-01-04 04:26:07

问题


I'm using this piece of code:

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)
            }
        }
    }
}

It worked fine in Swift 2.0, but after conversion it's not working anymore. This line:

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

is giving me the following error:

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

I've already tried some things but can't get it solved. Hopefully someone can help me.


回答1:


What the error

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

basically says is that your argument is of the wrong type ((CMSampleBuffer!, NSError!) -> Void) while it should be of the type ((CMSampleBuffer?, Error?) -> Void)!.

To achieve this, try using this code, it should automatically make your block conform to the right type:

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

It looks like a weird type but I think it's a little error Apple made somewhere while migrating this code from ObjC to Swift 1 to Swift 2 to Swift 3.
I haven't tested this code, but I think it should work, let me know if it actually did!




回答2:


In swift 3 that command changed!

from:

captureStillImageAsynchronouslyFromConnection

to:

captureStillImageAsynchronously

so try this code:

self.stillCameraOutput?.captureStillImageAsynchronously(from: connectionVideo, completionHandler: {
         (sampleBuffer, error) in
  // do your stuff here
}


来源:https://stackoverflow.com/questions/39492339/swift-3-photo-capturing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!