Diego Diego - 1 month ago 8
iOS Question

Delegate and UIActivityIndicatorView error



And just that I'm exercising the delegated pattern. I created a simple application where a delegate sends a message to UIViewController saying if you stop or start UIActivityIndicatorView. Unfortunately I get the following error: error atal: unexpectedly found nil while unwrapping an optional value.
It would seem that UIActivityIndicatorView is not initialized. I can not understand where I'm wrong.

protocol ProgressBarDelegate {
func UpdateProgressBar(progress: Bool)
}


class Dao: NSObject {

var delegate: ProgressBarDelegate?
override init() {
super.init()
//DELEGATO
//I who should I send the message? to FirstViewController
let messaggero = FirstViewController()
self.delegate = messaggero
scriviUnMessaggio(progress: true)
}
func scriviUnMessaggio(progress: Bool){
print("I'm writing a message ...")
delegate?.UpdateProgressBar(progress:progress)
}


My controller

class FirstViewController: UIViewController,ProgressBarDelegate {

@IBOutlet var activity: UIActivityIndicatorView!

func UpdateProgressBar(progress: Bool){

print("I received the message from Dao class (the delegate)")

switch progress{
case true:
// At this point I get the following error:Fatal error: unexpectedly found nil while unwrapping an Optional value


self.activity.startAnimating()
case false:
self.activity.stopAnimating()
default:
self.activity.startAnimating()
}
}

override func viewDidLoad() {
super.viewDidLoad()

let dao = Dao()

/// dao.caricamentoDati()

Answer

The problem is that you're creating a new object of FirstViewController in init of Dao. Since FirstViewController object is not created via xib/storyboard hence the outlet is not connected. That's why it's giving crash at self.activity.startAnimating()

Set the delegate to self in viewDidLoad

Change your Doa's init method as follow

class Dao: NSObject {

  var delegate: ProgressBarDelegate?
    init(delegate: ProgressBarDelegate) {
    super.init()
    //DELEGATO
    //I who should I send the message? to FirstViewController
    self.delegate = delegate
    scriviUnMessaggio(progress: true)
  }
  func scriviUnMessaggio(progress: Bool){
    print("I'm writing a message ...")
    delegate?.UpdateProgressBar(progress:progress)
}

Then in viewDidLoad do this

override func viewDidLoad() {
  super.viewDidLoad()
  let dao = Dao(delegate: self)
}
Comments