Anmol Rajpal Anmol Rajpal - 5 months ago 12
iOS Question

Unable to pass image to another UIViewController over present modally segue

I tried to pass an image to another imageView of destination UIView which is connected to source UIView over present Modally segue.

I tried to pass data through segue and as well set image (i.e. NSData - Core Data) in source UIView through Outlet but I got an error image description in console -


"fatal error: unexpectedly found nil while unwrapping an Optional
value"


//Code of destination UIView
import UIKit
import CoreData
class ReviewViewController: UIViewController {

@IBOutlet var backgroundImageView:UIImageView!
var subject:Semester!

override func viewDidLoad() {
super.viewDidLoad()
backgroundImageView?.image = UIImage(data: subject.image!)
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = view.bounds
backgroundImageView.addSubview(blurEffectView)

// Code of Source UIView
import UIKit
import CoreData

class SubjectDetailViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet var facultyImageView:UIImageView!
var subject:Semester!

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "destinationidentifier"
{
let destinationController = segue.destinationViewController as! ReviewViewController
destinationController.backgroundImageView?.image = self.facultyImageView.image
}
}

Answer

Your problem is backgroundImageView object is nil because destinationController is not currently in window hierarchy.

So Change your prepareForSegue like this

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "destinationidentifier"
    {
        let destinationController = segue.destinationViewController as! ReviewViewController
        destinationController.image = self.facultyImageView.image
    }
} 

Now create one image object in ReviewViewController like below and add one line in viewDidLoad

var image: UIImage!

override func viewDidLoad() {
    super.viewDidLoad()
    self.backgroundImageView?.image = self.image
}

Hope this will help you