swift - 使用堆栈和导航栏从 AppDelegate 推送到 ViewController
问题描述
我正在开发一个消息传递应用程序,但在实现推送通知行为时遇到了麻烦。
我想要的是,当用户点击通知时,该组的对话就会打开。但是必须有一个导航栏才能返回联系人列表。
我已经知道如何从通知中提取信息以获取联系人姓名。我正在 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)
这行不通。没有错误消息,但屏幕只是白色的。
这是我的故事板: 我使用 SWRevealViewController 作为侧边菜单,消息部分有一个 tabBarController,联系人列表位于 2º 选项卡上。
编辑:使用第二种方法,有一个错误。
无法将 'SWRevealViewController 类型的值转换为 UINavigationController'
解决方案
我认为您应该使用 NotificationCenter 来执行此操作。
当用户单击通知时,您应该在 didReceive 中发布 NotificationCenter,如下所示:
NotificationCenter.default.post(name: .onMessageRecieved, object: notificationObject)
根据您所在的视图控制器,您应该在 viewDidLoad() 函数中添加一个观察者,以便它了解已收到如下消息:
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(MyViewController.onMessageRecieved(notification:)), name: .onMessageRecieved, object: nil)
}
你应该在视图控制器中有一个 func (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)
}
这样您就可以从视图控制器进行导航,因此导航也将在那里。
推荐阅读
- javascript - 无法使用 react-pdf 查看 .pdf 文件
- c - _mm256_store_ps() 函数是原子的吗?在与 openmp 一起使用时
- solr - how to resolve solr create aliase error URI is too large?
- azure-devops - Azure DevOps Pipeline test showing partially succeeded
- python - 从给定列表中查找包含 int 值的缺失字符串
- python - 列值的两次出现并更新另一列的值
- typescript - 将 Testcafe 与 Appium 一起使用
- algorithm - making clusters dynamically so that if few data points are removed other clusters remain unaffected
- c# - How can I post data in database by showing data from another table in Dropdownlist
- reactjs - 如何在单击按钮时切换字段?