How do I handle universal links and custom URL schemes?

Handling universal links and custom URL schemes in your Swift application allows you to provide a seamless user experience by directing users to specific content or actions within your app. Universal links enable your app to open directly from websites, while custom URL schemes allow for deep linking from other apps.

Universal Links

Universal links work by associating your app with a specific domain. They do not require an explicit URL scheme to launch your app. Instead, you set up an apple-app-site-association file on your server which defines the paths that should be handled by your app.

Custom URL Schemes

Custom URL schemes are defined within your app's Info.plist file, allowing you to open your app via a specific URL. This method is older than universal links but still widely used for deep linking.

Example Implementation

This example demonstrates how to set up both universal links and custom URL schemes in your Swift application.

// Example for handling a universal link in AppDelegate.swift func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool { if let webpageURL = userActivity.webpageURL { // Process the URL and navigate to the appropriate content print("Universal link opened: \(webpageURL)") } return true } // Example for handling a custom URL scheme in AppDelegate.swift func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool { // Process the URL and navigate to the desired content print("Custom URL scheme opened: \(url)") return true }

universal links custom URL schemes Swift app deep linking mobile app development