-1

I added an activity indicator to my view controller via the main.storyboard and put it in my view controller via drag & drop method but when I try to do something with addSubView I get this error.

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

On the line: view.addSubview(ActInd)

The project is running on Swift 5.0 and Xcode 10.3. Switching back to Swift 4.2 makes no difference. I can debug the app but then it crashes when it comes to the piece of coding

import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate {
    var webView: WKWebView!

    @IBOutlet weak var ActInd: UIActivityIndicatorView!

    override func loadView() {
        webView = WKWebView()
        webView.navigationDelegate = self

        view = webView
    }

    func loadPage(){
        let url = URL(string: "SOMEURL")!
        webView.load(URLRequest(url: url))
        webView.allowsBackForwardNavigationGestures = true
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(ActInd)
        ActInd.startAnimating()
        ActInd.hidesWhenStopped = true

        loadPage()
    }

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
       // Code runs when its finnished
        ActInd.stopAnimating()



    }    
}

I wanted to have an activity indicator when my page was loading in the webview

Simon
  • 474
  • 2
  • 4
  • 20
  • 1
    Possible duplicate of [What does "fatal error: unexpectedly found nil while unwrapping an Optional value" mean?](https://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu) – RajeshKumar R Sep 16 '19 at 11:11
  • I saw that post, but it didn't really come out. Have several friends of mine look at mine code and that post but they did not come out either. Hence this post from me – Simon Sep 16 '19 at 11:13
  • 1
    Set a breakpoint in `viewDidLoad`. What's the value of `ActInd` at the time you're calling `addSubview`? Make sure it's non-nil. – Gereon Sep 16 '19 at 11:22
  • 1
    Your code doesn't make sense - if you are using an `@IBOutlet` and adding the activity view in the storyboard then you don't need to call `addSubview` - it will be added to the view hierarchy automatically. If you want to create the activity view programmatically and add it to the view hierarchy then you need to actually allocate an instance. You also don't use `loadView` if you are using a storyboard. – Paulw11 Sep 16 '19 at 11:27

1 Answers1

3

It seems, var ActInd: UIActivityIndicatorView! is nil

First of all, you should check whether you correctly defined you ActInd: UIActivityIndicatorView in the storyboard. Possibly, you didn't drag the item from storyboard(xib) file to the swift ViewController file.

And don't forget to use super methods.

override func loadView() {
super.loadView()
}
Vyacheslav
  • 26,359
  • 19
  • 112
  • 194