0

当使用 UTI 导入文件打开应用程序时,我有一个在场景委托中运行的代码。代码工作正常,但应用程序必须正在运行并加载视图控制器才能执行,我该怎么做才能在应用程序通过单击文件启动时运行代码?

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()
          }
      }
  }
//....
4

1 回答 1

0

设法修复它,对于任何有同样问题的人,添加这个,现在 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)
}
于 2020-08-11T12:41:42.420 回答