J Norris J Norris - 1 month ago 8
Swift Question

Error when I try to use NSTimer to change View Controller(EXC_BAD_INSTRUCTION)

I am trying to change a view controller after an animation. I used an

NSTimer
to change the view controller after the animation is done. The animation takes place on the default
ViewController
given. After this animation runs once, it's supposed to use the
prepareForSegue
function and go to the second view controller. When I run it, the animation works, but it doesn't change view controllers.

enter image description here

import UIKit

class ViewController: UIViewController, UIViewControllerTransitioningDelegate {
@IBOutlet weak var imageView: UIImageView!

var timer = NSTimer()

override func viewDidLoad() {
super.viewDidLoad()

var imagesNames = ["stairs", "stairs2", "stairs3", "stairs4", "stairs5", "stairs6", "stairs7", "stairs8", "stairs9", "stairs10", "stairs11", "stairs12", "stairs13", "stairs14", "stairs15", "stairs16", "stairs17", "stairs18", "stairs19", "stairs20", "stairs21", "stairs22", "stairs23", "stairs24", "stairs25", "stairs26", "stairs27", "stairs28", "stairs29", "stairs30", "stairs31", "stairs32", "stairs33", "stairs34", "stairs35", "stairs36", "stairs37", "stairs38", "stairs39", "stairs40", "stairs41", "stairs42", "stairs43", "stairs44", "stairs45", "stairs46","stairs47", "stairs48", "stairs49", "stairs50", "stairs51","stairs52", "stairs53", "stairs54", "stairs55", "stairs56","stairs57"]

var images = [UIImage]()

for i in 0..<imagesNames.count{
images.append(UIImage(named: imagesNames[i])!)
}

imageView.animationImages = images;
imageView.animationDuration = 4;
imageView.startAnimating()

_ = NSTimer.scheduledTimerWithTimeInterval(4.0, target: self, selector: #selector(timeToMoveOn), userInfo: nil, repeats: false)
}

func timeToMoveOn() {
self.performSegueWithIdentifier("goToMainUI", sender: self)
}

Answer

There's a clue in the console output in your screenshot.

You're implicitly unwrapping imageView but it is nil. This probably means that there's no image view connected to that outlet.

Comments