我试图在用户点击本地通知时显示详细视图控制器。
到目前为止,我知道:
//AppDelegate.swift
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
if let id = userInfo["item_id"] as? Int {
if let item = ItemsRepository.shared.getItem(id: id) {
let vc = DetailTableViewController()
vc.item = item
let tabController = self.window?.rootViewController as! UITabBarController
let navigationController = tabController.selectedViewController as! UINavigationController
navigationController.pushViewController(vc, animated: true)
}
}
completionHandler()
}
此代码生成异常,原因如下:
libc++abi.dylib: terminating with uncaught exception of type NSException
版本2
`
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
if let id = userInfo["item_id"] as? Int {
if let item = ItemsRepository.shared.getItem(id: id) {
let vc = DetailTableViewController()
vc.item = item
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "DetailView") as! DetailTableViewController
vc.item = item
window?.rootViewController = vc
self.window?.makeKeyAndVisible()
}
}
completionHandler()
}
它有点工作,但标签栏和导航控制器不再可见!
我在这里做错什么了?
最佳答案
而不是let vc = DetailTableViewController()
试试这个
let storyboard = UIStoryboard(name: "MyStoryboardName", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "someViewController")
告诉我这是否有效