iosswiftappdelegateurl-schemeuiscenedelegate

Opening content from URL Scheme when App is closed


My issue

I'm implementing URL Schemes in my application and they're overall working fine when the app is in the foreground or the background. However, I've noticed that when it is completely closed and another app tries to access content using my URL (eg. app:page?image=1 ) which would normally work, it just opens the app but the content is never caught.

My Approach

I've set up code in both my AppDelegate and SceneDelegate methods

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

And

func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {

Desired behavior

It opens when the app is in the background, foreground or closed

Actual behavior

It only opens when in foreground or background


Solution

  • Since your app is currently not running, it will be launched with those launch options. i.e. those options will be passed to willFinishLaunchingWithOptions: / didFinishLaunchingWithOptions: instead. Add you code to one of these methods.

    For more information, read documentation about how to Respond to the Launch of Your App, or, more specifically Determine Why Your App Was Launched.

    EDIT:

    As commented by @paulw11 below, scene delegate works differently, and must be handled separately.

    However, in Respond to Scene-Based Life-Cycle Events section, the last point is:

    In addition to scene-related events, you must also respond to the launch of your app using your UIApplicationDelegate object. For information about what to do at app launch, see Responding to the Launch of Your App

    So I assume, we still need to handle launch in willdidFinishLaunchingWithOptions / didFinishLaunchingWithOptions.