Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass data when dismiss modal viewController in swift

I'm trying to pass data from the modal ViewController to his source ViewController. I think I have to use delegation but it doesn't work.

protocol communicationControllerCamera{
    func backFromCamera()
}

class Camera: UIViewController{
    var delegate: communicationControllerCamera

    init(){
        self.delegate.backFromCamera()
    }
}


class SceneBuilder: UIViewController, communicationControllerCamera{
    func backFromCamera(){    // Never called
        println("YEAHH")
    }
}

The backFromCamera method it's not called. What did I do wrong?

like image 821
Marco Avatar asked Sep 10 '14 07:09

Marco


1 Answers

You didn't set a delegate so it was empty when you tried to call backFromCamera().

Here's a simple working example you can test out. Notice the use of the optional type (?) for the delegate.

// Camera class
protocol communicationControllerCamera {
    func backFromCamera()
}

class Camera: UIViewController {
    var delegate: communicationControllerCamera? = nil

    override func viewDidLoad() {
        super.viewDidLoad()
        self.delegate?.backFromCamera()
    }
}



// SceneBuilder class
class SceneBuilder: UIViewController, communicationControllerCamera {

   override func viewDidLoad() {
       super.viewDidLoad()
   }

   override func viewDidAppear(animated: Bool) {
       super.viewDidAppear(animated)

       var myCamera = Camera()
       myCamera.delegate = self

       self.presentModalViewController(myCamera, animated: true)
   }

   func backFromCamera() {
       println("Back from camera")
   }
}

You can find all the information you need in Apple's Swift documentation.

like image 105
Gad Avatar answered Oct 12 '22 15:10

Gad