0

I want to show push notification in a specific view controller when tap on notification and also want to send data from notification to view controller. I am using swift for development

Aashutosh Kumar
  • 183
  • 4
  • 12
  • already answered before check this: http://stackoverflow.com/questions/34856605/open-specific-viewcontroller-when-opening-app-from-push-notification – Jaafar Barek Apr 26 '17 at 06:32

2 Answers2

0

You should implement router for your view controllers which will be listening to notification send from app delegate and he will decide what to do. This is how I would do it, might be a better solution.

Luzo
  • 1,336
  • 10
  • 15
0

As @luzo pointed out, Notifications are the way to send to communicate to view controller(s) that an event has happened. The notification also has a userinfo parameter that accepts a dictionary of data you would like to send together with the notification to the view controller.

In Swift 3, add this to the tap button:

let center = NotificationCenter.default
center.post(name: Notification.Name(rawValue: "nameOfNotification"),
                    object: nil,
                    userInfo:["id":"data"])

And in the viewcontroller, register for the id of the notification and add a function reference:

    let center = NotificationCenter.default
    center.addObserver(forName:NSNotification.Name(rawValue: "nameOfNotification"), object:nil, queue:nil, using:notifDidConnect)

and add the function implementation:

 func notifDidConnect(notification:Notification) -> Void {
        guard let userInfo = notification.userInfo,
            let id  = userInfo["id"] as? String else {
               print("error occured")
               return
             }
        print("notification received")
    }
the_legend_27
  • 571
  • 4
  • 11