Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger function in VC when modal view is dismissed

I’m trying to trigger a function after dismissing a modal VC (FirstStartVC) back to the main VC. I know that I have to use delegation but it doesn’t work and my debug area stays empty.

In other question topics there were people who had it work exact the same way like below. So I have no idea what I’m doing wrong. Does anyone know what I need to change to the code?

//  FirstStartVC.swift
//

import UIKit
import CoreData
import JSSAlertView

protocol NewUser: class {
    func newUserAction()
}

class FirstStartVC: UITableViewController, UITextFieldDelegate {

    var delegation : NewUser?

    func saveNewUser(){
            self.delegation?.newUserAction()
            self.dismiss(animated: true, completion: nil)
        }
    }

    @IBAction func saveSettings(_ sender: Any) {
        self.saveNewUser()
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        print (delegation)

    }
}





//
//  ViewController.swift
//

import UIKit
import UserNotifications
import GoogleMobileAds
import CoreData
import JSSAlertView

class ViewController: UIViewController, UNUserNotificationCenterDelegate, NewUser {
    func newUserAction() {
        print("Reload some labels")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        var firstStart = FirstStartVC()
        firstStart.delegation = self

    }
}
like image 955
Luke P Avatar asked Jan 12 '17 16:01

Luke P


2 Answers

Swift 3

In your main VC viewDidLoad add:

NotificationCenter.default.addObserver(self, selector: #selector(mainVc.functionName), name:"NotificationID", object: nil)

and add a function in main VC

func functionName() {

    // Do stuff

}

in FirstStartVC call the method with

NotificationCenter.default.postNotificationName("NotificationID", object: nil)

Hope this helps!


A simple edit on Swift 4

NotificationCenter.default.addObserver(self, selector: #selector(self.funcName), name: NSNotification.Name(rawValue: "NotificationID"), object: nil)

Put @objc before the function definition.

@objc func functionName() {

    // Do stuff

}
like image 120
Jerland2 Avatar answered Oct 27 '22 09:10

Jerland2


In your code, you have:

func saveNewUser(){
        self.delegation?.newUserAction()
        self.dismiss(animated: true, completion: nil)
    }
}

Simply write the code you want to run after dismissing in completion::

func saveNewUser() {
        self.delegation?.newUserAction()
        self.dismiss(animated: true, completion: { finished in
            // on completion
        })
    }
}

(You might not even need to say finished in or anything like that.)

like image 41
Daniel Avatar answered Oct 27 '22 09:10

Daniel