Использование NotificationCenter для запуска UIAlertController в другом представлении - PullRequest
0 голосов
/ 05 февраля 2019

У меня есть два ViewController (ViewController - первый; SecondViewController - второй), встроенный в контроллер навигации.

В ViewController имеется наблюдатель NotificationCenter в viewDidLoad.

На SecondViewController у меня есть кнопка, которая должна публиковать уведомление в ViewController, которое при повторном появлении запускает UIAlertController.

ViewController:

class ViewController: UIViewController {

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

    func addObservers(){
        NotificationCenter.default.addObserver(self, selector: #selector(alertThankYou), name: Notification.Name(rawValue: Constants.handleThankYouNotif), object: nil)
    }
    func removeObservers(){
        NotificationCenter.default.removeObserver(self, name: Notification.Name(rawValue: Constants.handleThankYouNotif), object: nil)
    }

    @objc func alertThankYou(notification: Notification) {
        self.view.backgroundColor = .red
        let alertController = UIAlertController(title: "THANK YOU", message: "lorem ipsum dolor sit amet.", preferredStyle: .alert)
        let okAction = UIAlertAction(title: "Done", style: UIAlertAction.Style.default) { (result : UIAlertAction) -> Void in
            print("done pressed")
        }
        alertController.addAction(okAction)
        self.present(alertController, animated: true, completion: nil)
    }

    deinit {
        removeObservers()
    }

}

SecondViewController:

class SecondViewController: UIViewController {

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

    // Press this first to post the Notification!
    @IBAction func TRIGGERPOSTPRESSED(_ sender: UIButton) {
        NotificationCenter.default.post(name: Notification.Name(Constants.handleThankYouNotif), object: nil)
    }

    // Then press this to return back to ViewController to HOPEFULLY see an Alert.
    @IBAction func close(_ sender: Any) {
        if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
            appDelegate.window?.rootViewController?.dismiss(animated: true, completion: nil)
            (appDelegate.window?.rootViewController as? UINavigationController)?.popToRootViewController(animated: false)
        }
    }

}

Проблема: Вкл. SecondViewController, когда нажата TRIGGERPOSTPRESSED, я получаю это предупреждение в консоли:

Предупреждение:Попытка представить UIAlertController на ViewController, чье представление не находится в иерархии окон!

Что должно произойти: Вкл. SecondViewController, когда нажата TRIGGERPOSTPRESSED, я не должен получитьлюбые ошибки.Затем, когда нажата close, и приложение возвращается к ViewController, я должен получить предупреждение!

Как этого добиться с помощью NotificationCenter?

Ответы [ 2 ]

0 голосов
/ 06 февраля 2019

Пожалуйста, отправьте уведомление о завершении при отклонении SecondViewController.Фрагмент кода:

@IBAction func close(_ sender: Any) {
    if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
        appDelegate.window?.rootViewController?.dismiss(animated: true, completion: {
            NotificationCenter.default.post(name: Notification.Name(handleThankYouNotif), object: nil)
        })
        (appDelegate.window?.rootViewController as? UINavigationController)?.popToRootViewController(animated: false)
    }
}

The alert pop up

0 голосов
/ 05 февраля 2019

Думаю, вам не следует использовать NotificationCenter , в этом случае вам следует использовать Шаблон протокола делегатов , как и в предыдущем вопросе о Центр уведомлений и делегирование в iOS SDK и, конечно, это не производитель проблем, но правильная практика - использовать Делегирование, когда вам нужны только два класса для общения.

...