swift - 使用堆栈和导航栏从 AppDelegate 推送到 ViewController

标签 swift uiviewcontroller push-notification appdelegate

我正在开发消息传递应用程序,但在实现推送通知行为时遇到了问题。

我想要的是当用户点击通知时,该组的对话打开。但是必须有一个导航栏才能返回到联系人列表。

我已经知道如何从通知中提取信息以获取联系人姓名。我正在 AppDelegate 的 didReceive 函数中尝试这个。

到目前为止,我尝试过的是:

let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ChatViewController") as! ChatViewController
vc.contactName = name as String
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.rootViewController = vc
self.window?.makeKeyandVisible()

这会打开正确的对话并显示消息,但 UI 元素没有响应(点击文本字段时无法写入,点击按钮时无法导航到图库等)并且也没有导航栏。

所以在做了一些研究之后,我尝试了这个:

let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ChatViewController") as! ChatViewController
vc.contactName = name as String
let rootViewController = self.window?rootViewController as! UINavigationController
rootViewController. pushViewController(vc, animated: true)

这行不通。没有错误消息,但屏幕是白色的。

这是我的 Storyboard: enter image description here 我在侧面菜单中使用 SWRevealViewController,消息传递部分有一个 tabBarController,联系人列表在 2º 选项卡上。

编辑:第二种方法有错误。

Could not cast value of type 'SWRevealViewController to UINavigationController'

最佳答案

我认为您应该使用 NotificationCenter 来执行此操作。

当用户点击通知时,您应该像这样在 didReceive 中发布一个 NotificationCenter:

NotificationCenter.default.post(name: .onMessageRecieved, object: notificationObject)

并且根据您所在的 View Controller ,您应该在 viewDidLoad() 函数中添加一个观察者,以便它了解已收到如下消息:

override func viewDidLoad() {
        super.viewDidLoad()

        NotificationCenter.default.addObserver(self, selector: #selector(MyViewController.onMessageRecieved(notification:)), name: .onMessageRecieved, object: nil)

}

你应该在 View Controller 中有一个函数(onMessageRecieved)来做这样的导航:

    func onMessageRecieved(notification: NSNotification){

            // open the conversation

            let vc = self.storyboard?.instantiateViewController(withIdentifier: "ChatViewController") as! ChatViewController

            vc.contactName = name as String 

            self.navigationController?.pushViewController(vc, animated: true)

   }

通过这种方式,您可以从 View Controller 进行导航,因此导航也将在那里。

关于swift - 使用堆栈和导航栏从 AppDelegate 推送到 ViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55099390/

相关文章:

c - 如何在 Swift 中实现 AudioServicesSystemSoundCompletionProc?

ios - 如何将 ViewController 部分呈现在另一个 ViewController 上并且仍然能够与底部的 ViewController 交互?

ios - iPad 模拟器上的 SKScene 问题无法填满 Xcode 11 beta 7 中的屏幕

ios - `isRegisteredForRemoteNotifications` 第一次查询时返回 false

ios - 处理多个推送通知时出错

android - 其中一台移动设备未收到 GCM 通知

swift - 如何在嵌入的 tableView 上实现编辑/删除行为?

ios - 具有多个选项的 Swift 动画 UIView

ios - 更新数组内结构中的属性

ios - 访问页面 View Controller 上的属性