Home > Enterprise >  How to get UIApplication and options dictionary when handling url callbacks in SwiftUI
How to get UIApplication and options dictionary when handling url callbacks in SwiftUI

Time:02-25

I understand that in SwiftUI lifecycle, we can handle url callbacks as follow:

var body: some Scene {
    WindowGroup {
        ContentView()
            .onOpenURL { (url) in
                        // Handle url here
                }
        }
}

However, I wonder how do we access the UIApplication instance and the options dictionary in the UIKit AppDelegate lifecycle method, i.e.

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {

In some cases, third party SDK requires passing in those fields, and I wonder how do we do that in SwiftUI.

CodePudding user response:

You’re right, some features that previously required an app delegate in UIKit world now have alternative approaches in SwiftUI. However, in some cases we do still need an app delegate; but whereas one is created for you in the starting code for new UIKit apps, for SwiftUI apps we have to create it for ourselves.

First, create a class that inherits from NSObject and conforms to UIApplicationDelegate:

class AppDelegate: NSObject, UIApplicationDelegate {
  func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil
  ) -> Bool {
    // your code goes here
    return true
  }
}

Then, in your SwiftUI App struct, use the @UIApplicationDelegateAdaptor property wrapper to connect the class to your app:

@main
struct MyApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

CodePudding user response:

Use onContinueUserActivity

@main
struct TestApp: App {

    var body: some Scene {
        WindowGroup {
            ContentView()
            .onContinueUserActivity(NSUserActivityTypeBrowsingWeb, perform: handleUserActivity)
        }
    }

    func handleUserActivity(_ userActivity: NSUserActivity) {
        print(userActivity.webpageURL)
        print(userActivity.userInfo)
    }
}
  • Related