Search code examples
swiftwindowappdelegateutiuiscenedelegate

Swift Scene Delegate doesn't run code on first launch


I have a code which runs in Scene Delegate when opening the app using an UTI import File. Code works fine but the app has to be running and view controllers loaded for it to be executed, what can I do so the code is also ran when the app starts by clicking on the file?

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

Solution

  • Manage to fix it, for anyone having the same problem, add this, now the URL will be ran on first launch too!

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