Gulz
Gulz

Reputation: 1813

ios swift 3 addObserver how to redirect to a certain view from anywhere in the app when push notification tapped

I have an application which has tabBar with 5 tabs first one let's call it "FirstView" - has following code:

    override func viewWillAppear(_ animated: Bool) {
            ...
            NotificationCenter.default.addObserver(self, selector: #selector(self.catchIt), name: NSNotification.Name(rawValue: "myNotif"), object: nil)
        }



        override func viewWillDisappear(_ animated: Bool) {
            ...
            NotificationCenter.default.removeObserver(self)
        }

    override func viewDidAppear(_ animated: Bool) {
            ...
            NotificationCenter.default.post(name: Notification.Name(rawValue: "myNotif"), object: nil, userInfo: userInfo as [AnyHashable: Any])
        }
    }

I also have code in didReceiveRemoteNotification which ha this bit of code:

NotificationCenter.default.post(name: Notification.Name(rawValue: "myNotif"), object: nil, userInfo: userInfo as [AnyHashable: Any])

And I got UIViewController extension where I have catchIt() and defining redirections logic:

 func catchIt(_ userInfo: Notification) {
        let notification = userInfo.userInfo 
            if (path == "account.balance") {
                let vc: ProfileViewController = storyboard!.instantiateViewController(withIdentifier: "account.balance") as! ProfileViewController
                self.navigationController?.pushViewController(vc, animated: true)
//..and so on for other paths
      }
 }

This code has 2 problems: 1) Redirection only works if the last opened View was FirstView. if it is other View then I will never get redirected when taping push notification

2) I got my history when it is redirected but it tracks all the way down till the FirstView even if the destination controller is on the other tab different from the FirstViews (I tried to redirect first to required tab and then to destination controller but still it gives the track from the FirstView's tab)

I also tried to use didReceiveRemoteNotification - wrote all the redirections logic into it but it did not work

Would highly appreciate your advice

Upvotes: 1

Views: 602

Answers (1)

Ugo Marinelli
Ugo Marinelli

Reputation: 1039

The problem here, is that the post notification is called before the addObserver. That´s why nothing triggers.

SOLUTION :

Do not addObserver in your viewWillAppear but do it in the init method like this :

required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)!
    //Redirect for push notification
    NotificationCenter.default.addObserver(self, selector: #selector(self. catchIt), name: NSNotification.Name(rawValue: "myNotif"), object: nil)
}

Upvotes: 0

Related Questions