1

I am new to swift, I am writing an app which needs to change images in the storyboard. i have written a function to change images in the image view. In the function there is an if condition the image should be changed when the if condition is satisfied, but i got "unexpectedly found nil while unwrapping optional value" error when if condition is executed.

   import UIKit
   import MessageUI
   import Foundation
   import CoreLocation
    class ViewController: UIViewController {

   @IBOutlet var F_IMG: UIImageView!
   @IBOutlet var FL_IMG: UIImageView!
   @IBOutlet var FR_IMG: UIImageView!


   override func viewDidLoad() {
    super.viewDidLoad()

    TimeService.initial(viewcontroller: self)

    }

    public func showImages(){

       var type: String = Otherclass.gettype()

      setImageForType(type:type)


      }


      public  func setImageForType(type:String){

        if (type == "NONE"){

              DispatchQueue.main.async {

            self.F_IMG.image = UIImage(named: "r_f")

        }

"The showImage() function is called in another class."

I have the image in the bundle, but my UI is not getting updated and it always shows the error "unexpectedly found nil while unwrapping optional value"

3 Answers3

2

Make sure FrontImg is properly connected to Storyboard or correctly initialised through code.

Update:

As it turns out, you're calling showImages() from other class, hence it is giving nil error.

By calling ViewController.showImages() from other class, you are creating a new ViewController, not referencing an existing one. This new one doesn't have a F_IMG(imageView) yet because its view hasn't been built. You reference self.F_IMG.image is nil.

My advice is to use NSNotificationCenter for updating UI in other View Controller.

For more approaches, refer this SO Answer

Community
  • 1
  • 1
Arpit Dongre
  • 1,683
  • 19
  • 30
0

I believe the problem was caused in this line :

self.FrontImg.image = UIImage(named: "r_f")

If you check the Apple Docs on UIImage class, the initializer you are using init?(named name: String) actually returns optional.

So, have you tried

self.FrontImg.image = UIImage(named: "r_f")!
Vexy
  • 1,274
  • 1
  • 12
  • 17
0

The only thing here which I have found to make sure your UIElement FrontImg must be connected properly.

Sanoj Kashyap
  • 5,020
  • 4
  • 49
  • 75