1

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.

Alex
  • 620
  • 1
  • 6
  • 20
  • 2
    If the problem is solved, please either delete the question or answer it so as to close it out. – matt Jul 22 '20 at 22:57

1 Answers1

0

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)

    }
Alex
  • 620
  • 1
  • 6
  • 20