TransWikia.com

How to execute a function from second ViewController after popViewController?

Stack Overflow Asked on December 1, 2021

I am an Android developer trying to port my app to iOS and this is my first time working with Swift and Xcode, or anything Mac in general. The app is to scan for a QR code, if the QR code is invalid then I’d like it to go back to the previous screen and display a toast. I’ve already made a function that displays the toast stating the QR code was invalid.

func found(code: String) {
    print(code)
    // convert JSON to object
    do {
        let qrMessage = try JSONDecoder().decode(QrMessage.self, from: code.data(using: .utf8)!)
        print("QrMessage object - device name: " + qrMessage.pcName)
        
    }
    catch let error {
        print(error)
        _ = navigationController?.popViewController(animated: true)
        // call ShowInvalidQrToast() from the new VC that is now on top of the ViewController stack
    }

EDIT:
I managed to figure out a solution using the NotificationCenter from the first answer in this thread: Calling function from another ViewController in swift. More info in my answer below. If you think there is a better way of doing this, please post your own answer.

One Answer

My solution using NotificationCenter:

In ConnectViewController

override func viewDidLoad() {
    super.viewDidLoad()
    ...
    NotificationCenter.default.addObserver(self, selector: #selector(showInvalidQrCodeToast(_:)), name: Notification.Name(rawValue: "showInvalidQrCodeToast"), object: nil)

}

@objc func showInvalidQrCodeToast(_ notification: Notification) {
    self.view.makeToast("Invalid QR code")
}

In ScannerViewController

func found(code: String) {
    print(code)
    // convert JSON to object
    do {
        let qrMessage = try JSONDecoder().decode(QrMessage.self, from: code.data(using: .utf8)!)
        print("QrMessage object - device name: " + qrMessage.pcName)
        
    }
    catch let error {
        print(error)
        _ = navigationController?.popViewController(animated: true)
        NotificationCenter.default.post(name: Notification.Name(rawValue: "showInvalidQrCodeToast"), object: nil)

    }

Answered by Alex on December 1, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP