Swift Scene Delegate在首次启动时不会运行代码

问题描述

使用UTI导入文件打开应用程序时,我有一个在Scene Delegate中运行的代码代码可以正常运行,但是必须运行该应用程序并加载视图控制器才能执行该代码,我该怎么办,当通过单击文件启动该应用程序时也可以运行该代码

SceneDelegate.swift

class SceneDelegate: UIResponder,UIWindowSceneDelegate {

var window: UIWindow?


func scene(_ scene: UIScene,willConnectTo session: UIScenesession,options connectionoptions: UIScene.Connectionoptions) {

    guard let _ = (scene as? UIWindowScene) else { return }
}
func scene(_ scene: UIScene,openURLContexts URLContexts: Set<UIOpenURLContext>) {
      if let url = URLContexts.first?.url {
          // Handle URL
          let needTo = url.startAccessingSecurityScopedResource()

          do {
            let data = try Data(contentsOf: url)
            let contents = String(
              data: data,encoding: String.Encoding.utf8
            )
              if let x = contents
              {

                  MatchDecoder.decodeText(content: x)
                  
              }
          } catch(let error) { print(error) }

          if needTo {
            url.stopAccessingSecurityScopedResource()
          }
      }
  }
//....

解决方法

设法修复它,对于任何有相同问题的人,添加它,现在URL也将在首次启动时运行!

func scene(_ scene: UIScene,willConnectTo session: UISceneSession,options connectionOptions: UIScene.ConnectionOptions) {
    
    guard let _ = (scene as? UIWindowScene) else { return }
    self.scene(scene,openURLContexts: connectionOptions.urlContexts)
}