Swift : take photo from AVFoundation

╄→尐↘猪︶ㄣ 提交于 2019-12-05 21:23:55
alexsalo

Since code above didn't work I found an elegant solution in Swift.

Instead of this:

var videoConnection : AVCaptureConnection?
for connection in self.stillImageOutput.connections{
    for port in connection.inputPorts!{
        if port.mediaType == AVMediaTypeVideo{
            videoConnection = connection as? AVCaptureConnection
            break //for ports
        }
    }
    if videoConnection != nil{
        break //for connections
    }
}//take a photo then

You should use this: (updated for "output" spelling error)

if let videoConnection = stillImageOutput.connectionWithMediaType(AVMediaTypeVideo){//take a photo here}

Hope that helps!

Ok found the solution :

  func takePhoto(){




if let stillOutput = self.stillImageOutput {
    // we do this on another thread so that we don't hang the UI
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
        //find the video connection
        var videoConnection : AVCaptureConnection?
        for connecton in stillOutput.connections {
            //find a matching input port
            for port in connecton.inputPorts!{
                if port.mediaType == AVMediaTypeVideo {
                    videoConnection = connecton as? AVCaptureConnection
                    break //for port
                }
            }

            if videoConnection  != nil {
                break// for connections
            }
        }
        if videoConnection  != nil {
            stillOutput.captureStillImageAsynchronouslyFromConnection(videoConnection){
                (imageSampleBuffer : CMSampleBuffer!, _) in

                let imageDataJpeg = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageSampleBuffer)
                var pickedImage: UIImage = UIImage(data: imageDataJpeg)



            }
            self.captureSession.stopRunning()



        }
    }
}

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