【问题标题】:Swift Scene Delegate doesn't run code on first launchSwift Scene Delegate 在首次启动时不运行代码
【发布时间】:2020-08-11 12:02:02
【问题描述】:

当使用 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()
          }
      }
  }
//....

【问题讨论】:

    标签: swift window appdelegate uti uiscenedelegate


    【解决方案1】:

    设法修复它,对于任何有同样问题的人,添加这个,现在 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)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-15
      • 1970-01-01
      • 2016-12-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多