Reputation: 219
Learning Swift 4 and AVFoundation and coming across an error when the 'Take Photo' button has been tapped, throwing a 'Thread 1: EXC_BAD_ACCESS (code=1, address=0x596bbeb8)'
instead of navigating me to the preview view controller to show the image that was just captured.
(Happy to provide more code, just tried to pull out what i think might be relevant to keep question as short as possible :D)
In my ViewController.swift:
When the 'Take Picture' button is tapped, it called the takepicture() func.
func takePicture() {
let settings = AVCapturePhotoSettings()
cameraCaptureOutput?.capturePhoto(with: settings, delegate: self)
}
Then for the delegate:
extension ViewController : AVCapturePhotoCaptureDelegate {
func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
if let unwrappedError = error {
print(unwrappedError.localizedDescription)
} else {
let imageCaptured = photo.cgImageRepresentation()!.takeRetainedValue()
let finalImage = UIImage(cgImage: imageCaptured)
displayCapturedPhoto(capturedPhoto: finalImage)
}
}
}
The displayCapturedPhoto()
func:
func displayCapturedPhoto(capturedPhoto : UIImage) {
let imagePreviewViewController = storyboard?.instantiateViewController(withIdentifier: "imagePreviewViewController") as! imagePreviewViewController
imagePreviewViewController.capturedImage = capturedPhoto
navigationController?.pushViewController(imagePreviewViewController, animated: true)
}
In my imagePreviewViewController.swift:
var capturedImage : UIImage?
@IBOutlet weak var capturedImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
capturedImageView.image = capturedImage
// Do any additional setup after loading the view.
}
The error Thread 1: EXC_BAD_ACCESS (code=1, address=0x596bbeb8)
occurs on the capturedImageView.image = capturedImage
Can anyone point me in the right direction of where i may have gone wrong here?
Upvotes: 0
Views: 738
Reputation: 7187
AVCapturePhoto.cgImageRepresentation()
returns an Unmanaged CGImage Reference. If you takeRetainedValue()
on it you consume an unbalanced retain, which may cause it early release and subsequent EXC_BAD_ACCESS. Try takeUnretainedValue()
instead.
Upvotes: 1