点击Widget无法启动指定ViewController,始终打开默认页面问题求助
问题解决方案
- 适配不同生命周期的URL拦截逻辑
iOS 13及以上使用Scene生命周期的项目(Xcode 11+新建项目默认开启),URL回调默认不会走AppDelegate的application(_:open:options:)方法,需要在SceneDelegate中实现对应方法:
// 处理App在后台存活时的跳转 func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) { guard let url = URLContexts.first?.url, url.scheme == "fcv" else { return } let storyboard = UIStoryboard(name: "Main", bundle: nil) let vc = storyboard.instantiateViewController(withIdentifier: "WidgetActivity") as! WidgetActivityController // 不建议直接替换rootViewController,会清除用户之前的使用状态,推荐用push/present if let rootNav = window?.rootViewController as? UINavigationController { rootNav.pushViewController(vc, animated: true) } else { window?.rootViewController?.present(vc, animated: true) } } // 处理App完全冷启动时的跳转 func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { guard let urlContext = connectionOptions.urlContexts.first, urlContext.url.scheme == "fcv" else { return } // 调用和上面相同的跳转逻辑即可,建议封装为公用方法 }
如果你的项目未开启Scene生命周期,需要在AppDelegate的application(_:didFinishLaunchingWithOptions:)方法中,从launchOptions里读取UIApplication.LaunchOptionsKey.url字段,处理冷启动场景的跳转。
修正冗余配置
你配置的LSApplicationQueriesSchemes仅用于App跳转其他App时的白名单校验,自身接收自定义Scheme不需要配置该项,可以删除避免冗余。同时确认Target -> Info -> URL Types中填写的Scheme仅为fcv,不要额外加://后缀。校验Widget端URL有效性
URL(string:)会返回可选值,无效URL会被系统忽略,默认打开App首页,建议补充空校验:
.widgetURL(URL(string: "fcv://open_activity")!)
内容的提问来源于stack exchange,提问作者FelipeCruzV10
相关产品推荐
相关产品推荐

