ios - Swift 从今天扩展中的按钮打开特定的视图控制器
问题描述
我试图在今天的扩展中单击按钮打开特定的视图控制器,但无法显示它。主应用程序使用 url 方案在主根控制器上正确打开,但不是我在 App Delegate 中设置的特定视图控制器。
我尝试了所有可以在 Google 上找到的教程和答案,例如: How to open specific View controller on Widgets/Today Extension click
但我无法让它工作。我试图找出问题出在哪里,我认为应用程序委托中的方法没有调用。我写了一些 print() 方法,但没有一个出现在控制台中。我已经像上面链接的答案一样正确配置了 URL 方案,所以我不知道为什么 App Delegate 中的方法不执行。
希望有人有小费我还能尝试什么。
TodayViewController 中 Button IBAction 的代码:
@IBAction func addButtonOnePressed(_ sender: UIButton) {
let url = URL(string: "OpenURL://")!
self.extensionContext?.open(url, completionHandler: nil)
}
来自 App Delegate Method 的代码(我尝试了所有我能找到的):
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool
{
if url.scheme == "OpenURL"
{
let storyboard = UIStoryboard(name: "Groups", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "Group") as! MasterViewController
self.window?.rootViewController = vc
self.window?.makeKeyAndVisible()
}
return true
}
更新: 我自己解决了。我必须在 SceneDelegate 中而不是在 AppDelegate 中完成所有工作,并负责 Tabbar 控制器和导航控制器。
SceneDelegate.swift 中的新代码:
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
if let url = URLContexts.first?.url {
if url.scheme == "OpenURL" {
guard let rootViewController = (UIApplication.shared.connectedScenes.first?.delegate as? SceneDelegate)?.window?.rootViewController else {
return
}
let storyboard = UIStoryboard(name: "Groups", bundle: nil)
if let rootVC = storyboard.instantiateViewController(withIdentifier: "Group") as? MasterViewController,
let tabBarController = rootViewController as? UITabBarController,
let navController = tabBarController.selectedViewController as? UINavigationController {
navController.pushViewController(rootVC, animated: true)
}
}
}
}
解决方案
推荐阅读
- wordpress - 使用反向代理的重定向过多
- python - pymongo 批量写入执行速度很慢
- service-worker - angular pwa 8 ng serve refresh 引发错误
- matlab - 以图像看起来平坦的方式将图像投影到圆柱表面上
- django - 为什么 Django 在所有 {% url %} 模板标签查找中添加“/accounts/logout/”?
- javascript - 为什么我的承诺没有异步处理?
- javascript - 我们如何根据索引或通过 react-native flatlist 中的键检查/取消选中平面列表中的单个复选框
- reactjs - 路由器不在函数内部重定向
- php - 使用 Laravel 创建良好的 SEO 友好路线的问题
- actions-on-google - 将 Homegraph api 集成到我的智能家居中