Article

Handling Universal Links

Prepare your app to respond to an incoming universal link.

Overview

When a universal link is activated, iOS launches your app and sends it an NSUserActivity object. Query this object to find out how your app was launched and to decide what action to take.

To support universal links in your app, take the following steps:

  1. Create a two-way association between your app and your website and specify the URLs that your app handles. See Enabling Universal Links.

  2. Update your app delegate to respond when it receives an NSUserActivity object with the activityType set to NSUserActivityTypeBrowsingWeb.

Update Your App Delegate to Respond

When iOS opens your app as the result of a universal link, your app receives an NSUserActivity object with an activityType value of NSUserActivityTypeBrowsingWeb. The activity object’s webpageURL property contains the HTTP or HTTPS URL that the user accesses. Use NSURLComponents APIs to extract the components of the URL. For an example, see Listing 1.

Listing 1

An example of handling a universal link

func application(_ application: UIApplication,
                 continue userActivity: NSUserActivity,
                 restorationHandler: @escaping ([Any]?) -> Void) -> Bool
{
    guard userActivity.activityType == NSUserActivityTypeBrowsingWeb,
        let incomingURL = userActivity.webpageURL,
        let components = NSURLComponents(url: incomingURL, resolvingAgainstBaseURL: true),
        let path = components.path,
        let params = components.queryItems else {
            return false
    }
    
    print("path = \(path)")
    
    if let albumName = params.first(where: { $0.name == "albumname" } )?.value,
        let photoIndex = params.first(where: { $0.name == "index" })?.value {
        
        print("album = \(albumName)")
        print("photoIndex = \(photoIndex)")
        return true
        
    } else {
        print("Either album name or photo index missing")
        return false
    }
}

See Also

Universal Links

Enabling Universal Links

Configure your app and website to support universal links.