Universal links and incoming URLs
There are two kinds of links that open an app:
- Custom URL schemes, like
recipes://r/42. Easy to set up, but any app can register the same scheme, and if the app isn’t installed the link just fails. - Universal linksUniversal linkAn https link that opens your app when it's installed and your website when it isn't.Open in glossary →, normal web links like
https://recipes.example.com/r/42. If the app is installed, iOS opens the app; if not, the website opens. Nobody else can claim your domain.
Universal links need both sides to agree:
- The app lists the domain in its Associated Domains capability:
applinks:recipes.example.com. - The website serves a small JSON file, apple-app-site-association, at
https://recipes.example.com/.well-known/apple-app-site-association, saying which app and which paths may open.
When the link arrives, your app gets the URL and decides which screen to show. A link is input from the outside world, like a form field: check it before you trust it.
Universal links bind a domain to an app through two-sided verification: the Associated Domains entitlement (applinks:domain) and an apple-app-site-association (AASA) file served over HTTPS without redirects at /.well-known/. Since iOS 14, devices fetch AASA from Apple’s CDN rather than your server, at install and update and periodically after, so changes propagate with delay; applinks:domain?mode=developer on development builds bypasses the CDN. The components array matches paths, query items and fragments, with exclude rules evaluated in order. Behavior to explain to product: links tapped in the same domain inside Safari stay in Safari; typing the URL never opens the app; users can disable a domain by choosing “Open in Safari” from the long-press menu, and re-enable it through the smart banner. In SwiftUI, universal links arrive in .onOpenURL (or onContinueUserActivity(NSUserActivityTypeBrowsingWeb)). Treat every URL as untrusted input: parse into a typed route, validate ids and parameters, require authentication where needed (stash the route until login completes), and never perform state-changing actions from a link without user confirmation. Custom schemes remain useful for OAuth callbacks (ASWebAuthenticationSession) and app-to-app calls you control.
enum Route: Hashable {
case recipe(id: Recipe.ID)
case collection(id: Collection.ID)
}
extension Route {
/// Accepts only the links the app understands; everything else is ignored.
init?(url: URL) {
guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false),
components.scheme == "https",
components.host == "recipes.example.com" else { return nil }
let parts = components.path.split(separator: "/").map(String.init)
guard parts.count == 2, let id = Int(parts[1]), id > 0 else { return nil } // validate the id
switch parts[0] {
case "r": self = .recipe(id: id)
case "c": self = .collection(id: id)
default: return nil
}
}
}
@main
struct RecipesApp: App {
@State private var router = Router()
var body: some Scene {
WindowGroup {
RootView()
.environment(router)
.onOpenURL { url in // universal links and custom schemes
if let route = Route(url: url) { router.open(route) }
}
}
}
}// https://recipes.example.com/.well-known/apple-app-site-association (no .json extension, content-type application/json)
{
"applinks": {
"details": [
{
"appIDs": ["ABCDE12345.com.example.recipes"],
"components": [
{ "/": "/r/*", "comment": "recipes" },
{ "/": "/c/*", "comment": "collections" },
{ "/": "/account/*", "exclude": true, "comment": "handled by the website" }
]
}
]
}
}appIDsis your Team ID plus the bundle id.componentslists the paths the app handles;excludekeeps some on the website.Route(url:)turns a URL into one of the screens the app knows. Anything unexpected returnsniland is ignored, so a strange link can’t crash the app or open the wrong screen.router.open(route)is the same navigation code the app uses for taps (see Lists and navigation), so links reuse it instead of having their own.
Predict the output
The newsletter links to recipes://r/42 (a custom scheme) instead of https://recipes.example.com/r/42. What happens for a reader who doesn't have the app?
A custom scheme only works if an app that registered it is installed. There's no web fallback, and another app could even register recipes:// too. Universal links are normal https links: with the app installed they open it, otherwise the website, which can offer the App Store.
Practice: links that need a logged-in user
A link to /c/7 (a private collection) arrives while the user is logged out. The app should show the login screen, and after login, open the collection.
- Parse first:
Route(url:)gives.collection(id: 7). - Check the requirement: collections need an account. The router asks the session “logged in?” and gets no.
- Remember the route: store it as
pendingRouteand show the login screen. - After login: the router opens
pendingRouteand clears it. - Cold start: if the link launched the app, the same code runs once the root view appears, because
onOpenURLdelivers the URL then too.
Production puzzles
Predict the output
You add /deals/* to the AASA file and deploy it on Monday. The app is already installed on users' devices and hasn't been updated. On Tuesday, a push campaign links to https://recipes.example.com/deals/spring. Where does it open?
Devices don't fetch AASA from your server directly; Apple's CDN caches it and devices refresh it periodically and when the app is installed or updated. New paths can take days to apply everywhere. Ship AASA changes before campaigns (or alongside an app update), keep the website path working as a fallback, and test with ?mode=developer on development builds.
Tap the line with the bug.
.onOpenURL { url in
guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return }
let items = components.queryItems ?? []
if components.path == "/cart/add",
let id = items.first(where: { $0.name == "product" })?.value,
let qty = items.first(where: { $0.name == "qty" }).flatMap({ Int($0.value ?? "") }) {
cart.add(productID: id, quantity: qty)
router.open(.cart)
}
}Hint: Who can create this URL?
Anyone can: a web page, an email, an ad, another app (with a custom scheme). Opening the link changes the user’s cart with an unvalidated quantity, without the user asking for it. Combined with a link to checkout, that’s a real abuse path, and the same pattern on “follow”, “transfer” or “delete” endpoints is worse.
Links should navigate, not act: open the product screen with the suggested quantity pre-filled and let the user tap “Add to cart”. Validate ids and ranges either way, and keep state-changing operations behind explicit user interaction and server-side checks.
- Universal links:
applinks:entitlement + AASA at/.well-known/(HTTPS, no redirects) withcomponentsandexclude. Fetched via Apple’s CDN: changes lag;?mode=developerfor development. - Same-domain taps in Safari don’t open the app; typed URLs never do; users can opt out per domain.
- Custom schemes: no ownership, no fallback; fine for OAuth callbacks and app-to-app calls you control.
.onOpenURL→ typedRoute→ validate → router; stash routes that need login; handle cold starts.- Links navigate, never act: no state changes without user confirmation.
Check this part
What happens when someone taps a universal link and doesn’t have the app?
Which two things make universal links work?
A link like /cart/add?product=9&qty=50 adds items directly. What’s the problem?
A new AASA path doesn’t open the app for many users the next day. Likely reason?