CGImageRef is nil?
CGImageRef is nil?
I'm trying to take pictures in my app using AVFoundatin. In the didFinishProcessingPhoto block I run some code to gather the image data and create an image to show in the preview screen. Code included below:
didFinishProcessingPhoto
func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
if let error = error {
print("Error capturing photo: (error)")
} else {
let photoData = photo.fileDataRepresentation()
if let currentData = photoData {
let dataProvider = CGDataProvider(data: currentData as CFData)
let cgImageRef = CGImage(jpegDataProviderSource: dataProvider!, decode: nil, shouldInterpolate: true, intent: CGColorRenderingIntent.defaultIntent)
let image = UIImage(cgImage: cgImageRef!, scale: 1.0, orientation: self.getImageOrientation(forCamera: self.videoDeviceInput.device.position))
let containerView = PreviewPhotoContainerView()
self.view.addSubview(containerView)
containerView.previewImageView.image = image
containerView.snp.makeConstraints { (make) in
make.edges.equalTo(self.view)
}
}
}
}
However, every time I take a picture I get an error that something that is nil is being unwrapped. After some digging I found that it was CGImageRef. However, I can't see where I went wrong.
CGImageRef
photo.cgImageRepresentation()
UIImage
!
1 Answer
1
You can extract the image safely as below,
if let photoData = photo.fileDataRepresentation(), let image = UIImage(data: photoData) {
let containerView = PreviewPhotoContainerView()
self.view.addSubview(containerView)
containerView.previewImageView.image = image
containerView.snp.makeConstraints { (make) in
make.edges.equalTo(self.view)
}
}
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Why not use
photo.cgImageRepresentation()and create theUIImagefrom that? And stop using!. Safely unwrap optionals.– rmaddy
Jul 2 at 4:44