Swift Can't initializing UIImageView and causes fatal error: unexpectedly found nil - swift

I'm using xcode 8.2.1
fatal error: unexpectedly found nil while unwrapping an Optional value
This is the code,
class ShowMediaViewController: UIViewController {
var image: UIImage?
var titreText: String!
#IBOutlet var imageView: UIImageView!
//i tried #IBOutlet weak var imageView: UIImageView! but didn't work
#IBOutlet weak var titre: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
if image != nil {
//crashes here, because imageView is nil
imageView.image = image
} else {
print("image not found")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
The code seems to crash at this line
imageView.image = image
I think is because imageView is nil?, cause i tried
print(image)
and came out fine, and then
print(imageView), it causes fatal error
But i did initializing it
#IBOutlet var imageView: UIImageView!
Maybe something's wrong with my storyboard?
Any help would be much appreciated
**
UPDATE 1
Connection Inspector
pic 1
pic 2
**

I had the same problem. I tried following steps. then It works.
Try these things,
Check the imageView bind to the storyBoard properly.
Clean and Build the project.
if not works
Close and restart XCode
Remove imageView from storyBoard add again imageView and bind again.

You're probably missing a connection from your view to the outlet. Check these:-
1) clicking on a dot next to the outlet in the code shows a connection to the storyboard
2) the outlets window for the image shows a connection to the code

Related

Cannot get the SceneView to appear on ViewController

I am brand new to Swift so please go easy on me!
I am basically having trouble with rendering an ARKIT ARSCNView with getting the error:
Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value
Here is my code:
Initializing the view here by connecting to the Storyboard
#IBOutlet weak var sceneView: ARSCNView!
Here is the ViewDidLoad:
override func viewDidLoad() {
super.viewDidLoad()
setNeedsStatusBarAppearanceUpdate()
// crashes here
sceneView.delegate = self
}
Heres the ViewDidAppear:
override func viewDidAppear(_ animated: Bool) {
DispatchQueue.main.async {
self.animatePulsatingLayer()
self.dowloadModel()
}
}
The animatePulsatingLayer just plays an animation while the model is downloading.
The Download model just downloads the model to weak var node: SCNNode!
I have seen this code working before but since I have integrated SwiftUI into the project it has stopped working.
Any help would be appreciated.
This error mostly occurs when you remove or do not add the reference of the outlet with the .storyboard or .xib files.
I suggest you check them by right-clicking to the view on the storyboard and check if there is a connection.
Like this:
if there is no such connection you can simply connect them like this:

Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value [duplicate]

This question already has answers here:
What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?
(16 answers)
Closed 2 years ago.
My Swift program is crashing with a fatal error, saying that "Unexpectedly found nil while implicitly unwrapping an Optional value" even with the GUARD statement . Can anyone help to tell me why, and how do I fix it? The code as follows:
var page: Page? {
didSet{
guard let unwrappedPage = page else { return }
NameLabel.text = unwrappedPage.dishName
Image.image = UIImage(named: unwrappedPage.imageName)
contentText.text = unwrappedPage.ingredient
contentText.text = unwrappedPage.instruction
}
}
The issue is likely that the outlets have not been hooked up by the time you set page, and if these outlets are implicitly unwrapped optionals (with the ! after the type name, e.g. UILabel!), that will result in the error you describe. This problem will manifest itself if, for example, you set page before the view controller in question has been presented and all of the outlets have been hooked up.
So, I’d recommend:
Use optional chaining with your #IBOutlet references so it won’t fail if the outlets haven’t been hooked up yet.
Go ahead and keep your didSet observer on page, if you want, but make sure you also update the controls in viewDidLoad in case page was set before the outlets were hooked up.
For example:
#IBOutlet weak var nameLabel: UILabel!
#IBOutlet weak var imageView: UILabel!
#IBOutlet weak var ingredientLabel: UILabel!
#IBOutlet weak var instructionLabel: UILabel!
var page: Page? { didSet { updateControls(for: page) } }
override func viewDidLoad() {
super.viewDidLoad()
updateControls(for: page)
}
func updateControls(for page: Page?) {
nameLabel?.text = page?.dishName
imageView?.image = page.flatMap { UIImage(named: $0) }
ingredientLabel?.text = page?.ingredient
instructionLabel?.text = page?.instruction
}
Note, you only need this didSet observer if the page might be set (again) after the view has been presented. If not, the didSet observer is not needed.

How do I fix this bug in xCode?

No matter what program I run in xCode (as long as there is an #IBOutlet in the View Controller), I get the error fatal error: unexpectedly found nil while unwrapping an Optional value
In this case, my code is a simple image slideshow:
#IBOutlet weak var imageView: UIImageView!
override func viewDidAppear(animated: Bool) {
var imagesNames = ["image-3.jpeg","image-4.jpeg","image-5.jpeg","image-6.jpeg","image-7.jpeg"]
var images = [UIImage]()
for i in 0..<imagesNames.count{
images.append(UIImage(named: imagesNames[i])!)
}
imageView.animationImages = images
imageView.animationDuration = 0.05
imageView.startAnimating()
}
I'm not sure if I used viewDidAppear() correctly but it doesn't work if the code is in a viewDidLoad() as well. And yes, my #IBOutlet is connected in the storyboard with the little gray dot next to it filled in.
I have tried redownloading xCode. Should I try again?
Thanks
e
Maybe there is an unwanted outlet referenced in the storyboard...
It happens when a View has a referenced outlet that is missing in the uiviewcontroller code.
Make sure that all referenced outlets are linked to your UIViewController :
The only thing I can think of is if the force unwrapping of UIImage is finding nil for one of your images. To double check that it's not funny business on your end you should safely unwrap the image (which is good practice anyway). Try this and see if you're still getting the error:
override func viewDidAppear(animated: Bool) {
var imagesNames = ["image-3.jpeg","image-4.jpeg","image-5.jpeg","image-6.jpeg","image-7.jpeg"]
var images = [UIImage]()
for i in 0..<imagesNames.count {
guard let image = UIImage(named: imagesNames[i]) else {
print("\(imagesNames[i]) not found!"); continue
}
images.append(image)
}
imageView.animationImages = images
imageView.animationDuration = 0.05
imageView.startAnimating()
}
Try remove the unconnected outlet. probably you have remove variables in viewcontroller file but forgot to remove the connected outlet

Why am I getting a nil for a UITableViewCell's UILabel?

Why am I getting a 'nil' error/UILabel during my second pass thru the table cell listing iteration?
1) Inside cell
2) Inside cell
fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb) po cell?.contentView.viewWithTag(TitleLabelTag)
nil
Here I link the elements in the code; and register the cell:
class DiaryTableViewCell: UITableViewCell {
#IBOutlet weak var TitleLabel: UILabel!
#IBOutlet weak var SubTitleLabel: UILabel!
#IBOutlet weak var leftImageView: UIImageView!
#IBOutlet weak var rightImageView: UIImageView!
}
class DiaryTableViewController: UITableViewController {
let kCellIdentifier = "DiaryCell"
var cellNib:UINib?
var diaryCell:DiaryTableViewCell?
var objects = NSMutableArray() //...global var.
override func viewDidLoad() {
self.title = "My Diary"
cellNib = UINib(nibName: "TableViewCells", bundle: nil)
tableView.registerClass(DiaryTableViewCell.self, forCellReuseIdentifier: kCellIdentifier)
}
...
Yet I'm getting the runtime error here:
Here's what I get in the console:
1) Inside cell
fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb) po cell!.TitleLabel
nil
What's missing here?
It's a pretty bad idea to select a view with a tag. It's a much better idea to subclass your UITableViewCell and give it a property to access the elements.
If you are creating static cells and loading you need to create an IBoutlet for them in your .h correctly.
Moreover remove line
tableView.registerClass(...) statement from your code. Look at this link might help and is very similar except its for collectionview. -
Why is UICollectionViewCell's outlet nil?
1) I moved the cell registration to the viewDidLoad().
2) I forgot to place the '?' after the TitleLabel & SubTitleLabel; to notify the compiler that these labels could be nil.
I don't see the altered cell yet (empty rows); but I'm not getting runtime errors.
Unfortunately I merely cured the symptom; not the cause. I'm still getting nil UILabels.
...working on revision and cleaner code.

fatal error: unexpectedly found nil while unwrapping an Optional value - why?

I'm pretty new to coding in Swift and I'm not too sure what's happening here - can anyone help?
Thanks
import UIKit
class SecondViewController: UIViewController {
var toDoItems:[String] = []
#IBOutlet weak var toDoItem: UITextField!
#IBAction func addItem(sender: AnyObject) {
toDoItems.append(toDoItem.text)
fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)
println(toDoItems)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Most likely, your IBOutlet, toDoItem, was not bound successfully to a UITextField in Interface Builder. Check the outlets for your text field in Interface Builder and make sure it's hooked up successfully.
If the outlet is hooked up properly, another candidate source of this problem is the instantiation of the view controller itself. If you instantiated it programmatically (e.g. SecondViewController() instead of storyboard.instantiateViewControllerWithIdentifier(...)), that would also result in this error.