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
Related
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:
Hello I have ran into this situation before. I have image data that I want to pass from one view controller to another and display that data in an image view. In viewdidload in the 2nd VC, the data is printed properly but when I try to insert that data into 2nd VC imageview, the imageview is blank. You can see from the output that the printing the image data returns nil.
import UIKit
class ImageSelectedViewController: UIViewController {
#IBOutlet weak var imageView: UIImageView!
var imageViewData = Data()
override func viewDidLoad() {
super.viewDidLoad()
print(imageViewData)
imageView.image? = UIImage(data: imageViewData)!
print(imageView.image?.pngData())
}
Console:
205,397 bytes
nil
You need
imageView.image = UIImage(data: imageViewData)!
as ? here imageView.image? can make the whole line not effective
I am building a UITableView populated with images and GIFs downloaded using SDWebImage. The images are shown in the table cells, whereas the GIF are shown as a 3D touch preview.
The problem is that every time a GIF is previewed the memory spikes (as expected) however the memory use increases far more than I thought it would. Downloading one of the GIFs manually, I found that it's only around 500kB, but when doing it in the app through SDWebImage, sethe memory increase is closer to 100MB.
After just a few GIF previews the app crashes due to memory issues...
At first I thought perhaps the instance of GIFView was not being deallocated when the GIF preview was exited - I checked with '''deinit''' and it does seem to be deallocating.
I also reset the GIFView to '''nil''' in viewDidDisappear but that did not help either.
Looking at the Allocations Instrument, I found that the GIFs are being permanently stored in memory when they are first loaded. This explains why viewing the same GIF again does not increase the memory.
Does anyone see why these GIFs are taking so much memory? I also built a version of the app where all the assets were local and that ran smoothly with no hiccups or memory issues - but surely the GIF sizes should be the same size in both cases?!
If there is no leak and these memory spikes are inevitable, is there any other way of clearing the GIF from memory when it disappears?
Code is below
//model
struct Visualisation: Codable {
var id: Int
let name, info, url_name, tags, imageURL, gifURL: String
}
//3D touch GIF preview
extension ViewController: UIViewControllerPreviewingDelegate {
func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
guard let indexPath = tableView.indexPathForRow(at: location) else { return nil }
let selectedVis = filteredVisualisations[indexPath.row]
let identifier = "GIFViewController"
guard let GIFVC = storyboard?.instantiateViewController(withIdentifier: identifier) as? GIFViewController else { return nil}
GIFVC.selection = selectedVis
GIFVC.preferredContentSize = CGSize(width: 0, height: 190)
return GIFVC
}
//GIFViewController
import UIKit
import SDWebImage
class GIFViewController: UIViewController {
#IBOutlet weak var GIFView: UIImageView!
var selection = visualisations[0]
override func viewDidLoad() {
super.viewDidLoad()
GIFView.sd_setImage(with: URL(string: selection.gifURL))
// Do any additional setup after loading the view.
}
override func viewDidDisappear(_ animated: Bool = true) {
}
deinit {
print("DEALLOCATED GIFViewController class")
}
}
//setting the table cells
class TableViewCell: UITableViewCell {
#IBOutlet weak var ImageView: UIImageView!
#IBOutlet weak var TitleLabel: UILabel!
#IBOutlet weak var InfoLabel: UILabel!
func setCell(visualisation: Visualisation){
ImageView.sd_setImage(with: URL(string: visualisation.imageURL))
TitleLabel.text = visualisation.name
InfoLabel.text = visualisation.info
}
}
Any help would be much appreciated.
P.S. I am sure you've already noticed that I am very new to iOS development... Pardon my 'newbieness'...
I am creating a sort of manual slideshow (i.e., the pictures move when the user taps a forward or backward button), and it is made with a Collection View. I had to create a custom collection cell view class, which I finished, but now I'm getting an error message in the iOS Simulator, "fatal error: unexpectedly found nil while unwrapping an Optional value" even though my code builds successfully. The error is in the ibCollectionView.dataSource = self line, and because I'm new to Swift and OOP (I learned about a month ago for the first time), I am confused by this error message, especially because there are no ? operators. I have included the problem part of my code (the part Xcode showed with the error message) below. Thank you!
import UIKit
class FluidIntakeMainMenuViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
//MARK: - Collection View Properties
#IBOutlet weak var ibCollectionView: UICollectionView!
#IBOutlet weak var ibCollectionViewLayout: UICollectionViewLayout!
var cellArray:[customCollectionViewCell] = Array(repeatElement(customCollectionViewCell(), count: 6))
let displayedCellDimensions = CGSize(width: 343, height: 248)
//MARK: - Xcode-generated Methods
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
ibCollectionView.dataSource = self
ibCollectionView.delegate = self
}
//My code for this class continues down here...
First and most important thing is to check the IBOutlet connection
that you made in your storyboard.
Try to remove the connection in storyboard and then reconnect it.
Secondly put a debugger on to check if it's still nil.
ibCollectionView.dataSource = self
I think you forgot about this:
override func viewDidLoad() {
super.viewDidLoad()
// Register cell classes
ibCollectionView?.register(YourCustomCell.self, forCellWithReuseIdentifier: "Cell")
And use "Cell" identifier in cellForItemAt...
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