Tyler Pierog Tyler Pierog - 16 days ago 5
Swift Question

Taking a picture and passing it to a different UIViewController Swift 3.0

I'm trying to take an image in my app so I can save it to my device and pass it to the next view controller to be previewed. The way I see people doing this is storing the image they take in a uiimage. Then during prepareforsegue they set the uiimage variable in the destination view controller to the photo you took in the previous view controller. From there in the dest view controller I see people displaying the image as follows : imageName.image = imageVariable . When I pass the variable to the destination view controller and try to display it in the next view controller it appears as a nil value. Where am I going wrong?

First ViewController:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ToDetailPage" {
let nextScene = segue.destination as! PostDetailPageViewController
nextScene.itemImage = self.image
// nextScene?.myimg.image = self.image
}
}

@IBAction func TakePhotoButtonClicked(_ sender: AnyObject) {

if let videoConnection = sessionOutput.connection(withMediaType: AVMediaTypeVideo){

sessionOutput.captureStillImageAsynchronously(from: videoConnection, completionHandler: {
buffer, error in
let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(buffer)
self.image = UIImage(data: imageData!)
UIImageWriteToSavedPhotosAlbum(UIImage(data: imageData!)!, nil, nil, nil)
})

}


}


Second ViewController:

var itemImage: UIImage!
@IBOutlet weak var myimg: UIImageView!

override func viewDidLoad() {

super.viewDidLoad()
self.categories.dataSource = self;
self.categories.delegate = self;
setUpMap()
myimg.image = itemImage

}

Answer

You need to push viewController inside the block. Actually what is happening in this code the completion block is called after prepareForSegue. So your image is always 'nil'.

Try to push the viewController like this:

if let videoConnection = sessionOutput.connection(withMediaType: AVMediaTypeVideo){


sessionOutput.captureStillImageAsynchronously(from: videoConnection, completionHandler: {
        buffer, error in
            let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(buffer)
            self.image = UIImage(data: imageData!)
            UIImageWriteToSavedPhotosAlbum(UIImage(data: imageData!)!, nil, nil, nil)
// push view controller here
let destinationVC = SecondViewController()
destinationVC.image = self.image
self.navigationController.pushViewController(destinationVC, animated: true)
        })
 }

Hope it will help you.. Happy Coding!!

Comments