Ad

Simple Question About Delegate And View Controllers

- 1 answer

I have ViewContA (parent) and ViewContB (is a child from ViewContA)

ViewContA listen from firebase when user data change, So instantly i want that ViewContB have the data updated.

My Code

    protocol childVCDelegate {
        var user: User? { get set }
    }

    class ViewContA: UIViewController{
       
       var user: User?

       let VCB =  ViewContB()
       VCB.delegate = self

       //viewdidload
       loadUser()

       func loadUser(){
           // this function observe childChanged in realtime firebase
           UserService.shared.observeUser(uid: "XXX") { (user_updated) in
             // here update the user info in ViewContA but not in ViewContB
             self.user = user_updated
           }
       }

    }

    class ViewContB: UIViewController{
      
       var delegate: childVCDelegate
      
       var user: User?{
         delegate?.user
       }
       
       //viewdidload
       // USER IS ALWAYS THE SAME, NOT CHANGE WHEN FIREBASE FIRE loadUser in Parent
       print(user)

    }

thanks very much!

Ad

Answer

If you want to use the delegate design pattern so that view controller A notifies view controller B when the list of users from Firebase changes, then you should make view controller B be view controller A's delegate. Define a protocol, let's call it UsersProtocol, that has a method userHasChanged(_ user: User?). When the firebase completion handler fires, invoke the method:

protocol UsersProtocol {
    func userHasChanged(_ user: User?)
}


class ViewContA: UIViewController{

    var delegate: UsersProtocol? = nil

    func loadUser(){
           // this function observe childChanged in realtime firebase
           UserService.shared.observeUser(uid: "XXX") { (user_updated) in
             // here update the user info in ViewContA but not in ViewContB
             self.user = user_updated
             self.delegate?.userHasChanged(user_updated)
           }
       }
}

(Remember that you would need to set ViewContA's delegate to point to ViewContB.)

Ad
source: stackoverflow.com
Ad