收到推送通知时加载ViewController

时间:2016-03-13 17:39:07

标签: swift

当用户收到推送通知并点按通知时,他/她将被带入我的应用程序,我希望在其中显示某个视图控制器。因此我使用通知中心。

我的问题是,我需要在哪里执行加载视图控制器,以便在用户进入应用程序时显示并推送到导航堆栈?

func processReceivedRemoteNotification(userInfo:[NSObject:AnyObject]) {

    let notification = userInfo as! Dictionary<String, AnyObject>

    let json = JSON(notification)

    // Get information from payload
    let dispatchType:String = json["dispatch"]["dispatchType"].stringValue

    switch dispatchType {
    case "alert":
        self.notificationCenter.postNotificationName("ALERT_RECEIVED", object: nil, userInfo: userInfo as [NSObject:AnyObject])
        break
    default:
        break
    }
}

查看要加载的控制器

class AlertViewController: UIViewController {

    let notificationCenter: NSNotificationCenter = NSNotificationCenter.defaultCenter()

    override func viewWillAppear(animated: Bool) {
        self.notificationCenter.addObserver(self, selector: "alertMessageReceived:", name: "ALERT_RECEIVED", object: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func alertMessageReceived(notification: NSNotification) {
        let userInfo = notification.userInfo as! Dictionary<String, AnyObject>
        print(userInfo)
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let vc1: AlertViewController = storyboard.instantiateViewControllerWithIdentifier("example1") as! AlertViewController
        self.navigationController?.pushViewController(vc1, animated: true)
    }

1 个答案:

答案 0 :(得分:0)

我不知道您的应用程序架构,但从给定的上下文中我可以看到您有navigationController。在这种情况下,您不应该添加为观察者AlertViewController。而是将此代码移动到另一个视图控制器,该控制器已被推送到navigationController。另一种选择是继承UINavigationController并在其中观察"ALERT_RECEIVED"通知。