LoginSignup
3
1

More than 1 year has passed since last update.

【WidgetKit】SceneDelegateを使用せずにウィジェットからの遷移を実装したい

Last updated at Posted at 2021-08-19

はじめに

Widget内でLink.widgetURLを使用した場合、SceneDelegate内で処理を追加する必要があります。
AppDelegateのみで実装している場合、後からSceneDelegateを追加するのは面倒です。
そこで、なんとかAppDelegateでできないかなと模索しました。
なんとAppDelegateにUIWindowSceneDelegateを継承させて実装してあげると、なんと動いてしまいました。

実装方法

下記の例のようにAppDelegateにUIWindowSceneDelegateを継承させて実装します。

extension AppDelegate: UIWindowSceneDelegate {

    @available(iOS 14.0, *)
    // App launched
     func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
         guard let _: UIWindowScene = scene as? UIWindowScene else {
            return
         }
         maybeOpenedFromWidget(urlContexts: connectionOptions.urlContexts)
     }

    @available(iOS 14.0, *)
     // App opened from background
     func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
         maybeOpenedFromWidget(urlContexts: URLContexts)
     }

    @available(iOS 14.0, *)
     private func maybeOpenedFromWidget(urlContexts: Set<UIOpenURLContext>) {
         if let _: UIOpenURLContext = urlContexts.first(where: {
            $0.url.scheme == "widget-link"
         }) {
            print("🚀 Launched from widget")
         }
     }
}

最後に

AppdelegateにSceneDelegateの実装をしていいか分かりませんが、とりあえず動くので大丈夫でしょう(?)

3
1
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1