Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 46 ยท Navigation and App Structure

Deep Links and Universal Links

Open your iOS app from a URL: custom schemes, universal links, onOpenURL, and a safe router that turns a URL into a NavigationStack path.

A deep link is a URL that opens your app at a specific place: a product page, a chat, a settings screen. Links from emails, web pages, push notifications, QR codes and other apps all work this way. Getting them right means two jobs: letting iOS route the URL to your app, and turning the URL into a navigation state your app understands.

The first job is configuration in Xcode and on your web server, which cannot run here, so that part is read-only. The second job is plain Swift, and the TryIts build a small, testable URL router you can run.

Two kinds of link

Custom scheme shopapp://product/42. Easy, but anyone can claim a scheme.
Universal link https://shop.example/product/42. Verified, opens in the app.

Prefer universal links for anything public.

1 / 2

Custom URL schemes

A custom scheme such as shopapp:// is registered in the target's Info settings under URL Types. After that, any link starting with shopapp: is handed to your app.

It is simple, but it has real weaknesses:

  • No ownership. Any app can register the same scheme, so you cannot be sure the link reaches your app.
  • No fallback. If the app is not installed, the link does nothing useful, while a web URL could show a page or an App Store prompt.
  • Not for secrets. Anyone can craft such a URL, so you must treat it as untrusted input.

Custom schemes remain handy for internal flows, OAuth redirects and development. For links you share publicly, use universal links.

A universal link is an ordinary https URL on a domain you control. If your app declares that it handles the domain, iOS opens the app directly instead of Safari. If the app is not installed, the same URL simply opens your website, which is the big advantage.

Setting it up has two sides, and both must match:

  1. In the app: add the Associated Domains capability and an entry such as applinks:shop.example.
  2. On the website: serve a JSON file named apple-app-site-association at https://shop.example/.well-known/apple-app-site-association, over HTTPS, without redirects. It lists your app identifier (team ID plus bundle ID) and the URL paths the app handles.

iOS downloads that file when the app is installed or updated. Because only the real owner of the domain can publish the file, nobody else can claim your links. A common reason for "my universal link opens Safari" is a mismatched app identifier, a redirecting or non-HTTPS file, or a path that is not listed.

Links typed or pasted into Safari's address bar generally open the website rather than the app. Test universal links by tapping them in Notes, Messages or Mail instead.

Receiving the URL in SwiftUI

Both kinds of link arrive through the same modifier. Attach onOpenURL to a view in the scene:

Swift
@main
struct ShopApp: App {
    @State private var router = Router()

    var body: some Scene {
        WindowGroup {
            RootView()
                .environment(router)
                .onOpenURL { url in
                    router.open(url)
                }
        }
    }
}

The closure runs when the app is launched by a link and also when it is already running. Note what it does not do: it does not navigate. It forwards the URL to a router, and the router owns the navigation state. That separation keeps the parsing testable without any UI.

Universal links sometimes arrive as a user activity (for example when handed off from another device). onContinueUserActivity(NSUserActivityTypeBrowsingWeb) handles that case; its closure receives an activity whose webpageURL you pass to the same router.

Turning a URL into a route

Define the places a link may lead as a value type, then write a function that maps a URL to a route or to nil. Every incoming URL is untrusted input, so be strict.

Swift A URL router

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The router checks the scheme and host, demands an integer product ID, and returns nil for anything unexpected. Returning an optional is a deliberate design: the caller decides what to do with an unknown link (usually, show the home screen).

From a route to a navigation path

A NavigationStack with a path binding is ideal here: opening a deep link is just assigning to the path. A link to a product should usually show the product with a sensible back stack, so you build the path rather than just pushing one screen.

Swift
@Observable
final class Router {
    var path: [Route] = []

    func open(_ url: URL) {
        guard let destination = route(for: url) else { return }
        switch destination {
        case .product(let id):
            path = [.category(name: category(of: id)), .product(id: id)]
        default:
            path = [destination]
        }
    }
}

struct RootView: View {
    @Environment(Router.self) private var router

    var body: some View {
        @Bindable var router = router
        NavigationStack(path: $router.path) {
            HomeView()
                .navigationDestination(for: Route.self) { route in
                    switch route {
                    case .product(let id): ProductView(id: id)
                    case .category(let name): CategoryView(name: name)
                    case .settings: SettingsView()
                    }
                }
        }
    }
}

@Bindable creates the $router.path binding for an @Observable object (see @Observable and Observation). Replacing the whole path in one assignment is better than appending in a loop, because the UI updates once.

If the user is deep in another screen when a link arrives, replacing the path discards that position. That is usually what people expect from a link, but think about unsaved input: you may want to confirm first, or present the link target in a sheet.

Swift Opening links on top of a navigation path

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Pressing Back from a deep-linked product lands on its category, not on a blank screen, because the router built the whole stack.

Security and good habits

  • Validate everything. Parse with URLComponents, check the scheme and host, convert numbers with Int(...), and reject the rest. Never pass URL pieces straight into a database query, a file path or a web view.
  • Do not perform actions from a link. A link like shopapp://delete-account would let any web page trigger it. Links should navigate. Actions that change data need a confirmation in the app.
  • Do not put secrets in links. Tokens in URLs end up in logs and histories. If you must use a one-time code, make it short-lived and single-use.
  • Handle cold start. Links must work when the app is not running. Test by force-quitting the app and tapping a link.
  • Handle logged-out users. Decide whether to show a login first and remember the destination afterwards.
  • Keep links stable. Published URLs live in emails for years. Design the path structure once and keep supporting old forms.

In the simulator you can test a link from the command line with xcrun simctl openurl booted "<url>", and in Xcode you can set launch arguments, but for universal links the real device flow is the reliable check.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why are universal links preferred over custom schemes for public links?

    A universal link is an https URL that only the domain owner can connect to an app, and it still works as a web page when the app is not installed.
  2. 2. Which pieces are needed to make universal links work?

    The app declares the domain, the website publishes the association file, and iOS checks that both agree.
  3. 3. What should the onOpenURL closure usually do?

    The closure should forward the URL to a router that maps it to a route and sets the navigation path. Parsing in a router keeps it testable.
  4. 4. A link carries the path /product/abc. What should the router do?

    Incoming URLs are untrusted input. Validate every part and fall back to a safe destination when it does not match.
  5. 5. Why build a path like [category, product] for a product link instead of pushing only the product?

    A realistic back stack makes a deep-linked screen feel like part of the app's normal navigation.

Summary

  • A deep link opens the app at a specific place; custom schemes are easy but unverified, universal links are verified https URLs.
  • Universal links need the Associated Domains capability and an apple-app-site-association file served from your domain.
  • onOpenURL receives links for both kinds; forward the URL to a router rather than navigating inline.
  • Treat every URL as untrusted: check scheme and host, parse numbers strictly, and return nil for anything unexpected.
  • Deep links navigate; they should not trigger destructive actions or carry secrets.
  • Build the full navigation path so Back behaves naturally.

Next: Codable and JSON in iOS Apps