How to Implement Deep Links for Your Mobile Apps

What are Deep Links?

Deep links allow users to tap a link that would launch and navigate to a particular location within your app seamlessly.

These are valid links within your website that would be opened in the web browser in case your app isn’t installed on the user’s device.

Some real-life examples of Deep links in use are

  • Sending an email notification from your eCommerce in case there is card abandonment that takes the users directory to the shopping cart for a quick call to action
  • Links to product pages on your website, which would open the relevant product screen in the app, if installed.

Static and Dynamic Deep Links

There are two kinds of Deep links –

Static Links

These are regular static URLs that point to a specific location in the app, such as a product page or the user’s shopping cart.

Dynamic Links

Dynamic links allow you to pass parameters to your app so that some conditional action can be performed when your app launches and navigates to a specific location. A great example of this is linked with a coupon code that can launch the check-out page in your app and apply the coupon automatically for the user.

Dynamic links are a powerful way to pass data between apps and provide a seamless handoff from one app to another.

Why use Deep Links?

There are several benefits of using Deep Links in your app.

Superior User Experience: Deep links allow you to create a superior user experience. It removes the hassle of copy-pasting information from one app to another. It also reduces friction for users to launch and use your app.

Flexibility: Whether users have installed your app or not, deep links still work. If your app isn’t installed, the link will open in the system browser, to complete your transaction

Security: Deep links are verified by the OS (explained later) to be genuine before your app is launched. Your app is associated with your website and no other app can be launched with URLs from your domain. Similarly, your app will not be launched from unassociated URLs.

Inter-App Communication: Deep links allow apps to communicate with each other. They allow users to move from one app to another seamlessly. This is really helpful for example in cases such as payment scenarios where you have to launch a wallet app to complete your payment in the shopping app and return back again.

How to Implement Deep Links?

You can implement Deep links for Android and iOS using the native methods which require you to have access to the webserver of your application. You could also use a third-party service such as Firebase to do this.

In this article, we will explore both methods of implementing Deep links in your app for Android and iOS using Native platform methods as well as using a third-party service like Firebase.

Implementation using Native approach

Android

In the Android ecosystem, Deep links are called App Links.

These are the main steps to associate your website links with your app so they can launch the app directly without user selection.

Step 1. Register links in your app manifest

To allow your app to handle your URL scheme, intent filters need to be added to your app’s manifest file. Here is an example that would allow your app to handle URLs that would start with http://myappdomain.com/products/ or myappdomain://products

<activity
    android:name="com.myappdomain.android.products"
    android:label="@string/title_products" >
    <intent-filter android:autoVerify="true" android:label="@string/filter_view_http_gizmos">
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <!-- Accepts URIs that begin with "http://www.myappdomain.com/products" -->
        <data android:scheme="http"
              android:host="www.myappdomain.com"
              android:pathPrefix="/products" />
        <!-- note that the leading "/" is required for pathPrefix-->
    </intent-filter>
    <intent-filter android:label="@string/filter_view_example_gizmos">
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <!-- Accepts URIs that begin with "myappdomain://products" -->
        <data android:scheme="myappdomain"
              android:host="products" />
    </intent-filter>
</activity>
Step 2. Add code for handling links and incoming data in your app/activity.

Once your app is launched you can handle the incoming intent and retrieve parameters in the onCreate or onStart callback of your activity.

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.main)

    val action: String? = intent?.action
    val data: Uri? = intent?.data
}
Step 3. Setup verification for your deep links (App)

n order for your app to be able to handle the App link for your domain, you need to verify ownership of the domain and app. This is done using Digital Asset Links API, which establishes trust that your app is approved by your website to handle links for its domain.

Here are steps to do that:

Add the autoVerify handle attribute in your intent filter (See Step 1)
Prepare a Digital Assets Link JSON file. This file identifies the app association using the following fields
package_name which is the app ID you are using in your build.gradle file
sha256_cert_fingerprints which are the SHA256 fingerprints of your app’s signing certificate. You can use the following command to generate the fingerprint via the Java keytool
$ keytool -list -v -keystore my-release-key.keystore
The following example assetlinks.json file grants link-opening rights to a com.myappdomain Android app

[{
  "relation": ["delegate_permission/common.handle_all_urls"],
  "target": {
    "namespace": "android_app",
    "package_name": "com.example",
    "Sha256_cert_fingerprints": ["14:6D:E9:83:C5:73:06:50:D8:EE:B9:95:2F:34:FC:64:16:A0:83:42:E6:1D:BE:A8:8A:04:96:B2:3F:CF:44:E5"]}
}]
  • Declare associations between your website and intent filters Digital Asset Link JSON file hosted at the following URL

https://domain.name/.well-known/assetlinks.json
Which in case of our example would map to

https://myappdomain.com/.well-known/assetlinks.json
For more information on how to verify your app links refer to the Android documentation for Verifying App Links.

iOS

Deep links in the iOS ecosystem are called universal links.

Here are the steps to associate universal links with your app.

Step 1: Create an apple-app-site-association

To create a secure connection between your app and website, a trust relationship needs to be established between them by following these steps.

Add an apple-app-site-association file to each domain that your app is going to support
The apple-app-site-association contains a JSON that lists the paths from your website that the app will be handling.
This sample allows support for handling of links from myappdomain.com to be opened by two apps com.myappdomain.products (paths /products) and com.myappdomain.articles (path /articles and all child URLs under it)

{
   "applinks": {
       "apps": [],
       "details": [
           {
               "appID": "com.myappdomain.products",
               "paths": [ "/products"]
           },
           {
               "appID": "com.myappdomain.articles",
               "paths": [ "/articles/*" ]
           }
       ]
   }
}
  • You can also use wildcards to support a larger set of paths. You may also use the “NOT” keyword to exclude specific paths from a larger set. For example the paths array below will prevent the app to handle the /articles/internal/ area of the website
"paths": [ "/articles/news/", "NOT /articles/internal/*", "/articles/blogs/"]
Step 2: Deploy your app associate file to domain root

Upload the apple-app-site-association file to your HTTPS web server. You can place the file at the root of your server or in the .well-known subdirectory.

Remember that you do not need the .json extension for the apple-app-site-association file.

Step 3: Prepare your app to handle universal links.
In order to handle the universal links within your app your need to

Add an entitlement that specifies the domains your app supports

Update your AppDelegate callback to handled the NSUserActivity object

For more information on how to implement Universal links refer to the Apple developer guide documentation for Universal Links.

Implementation using Firebase

Using Firebase to create Deep Links makes it easier and faster to implement Deep Links for Android and iOS as Native specific steps are reduced.

Deep Links in the Firebase ecosystem are called Firebase Dynamic Links.

The main steps to get Firebase Dynamic Links setup for your app are as follows.

Step 1: Create Dynamic Links

You can create Dynamic Links that your app would require to handle in the following ways

  • Using the Firebase Console – this is suitable for a one-off link generation such as promo codes or special announcement links that you would create for your app
  • This can be done programmatically using the Firebase Dynamic Link Builder API for iOS and Android. This is more suitable when user generated Dynamic Links need to be created at scale.
  • Using the Rest API – in case you are not using the Builder API
  • Manually – you can use the standard deep link format

https://your_subdomain.page.link/link=your_deep_link&apn=package_name[&amv=minimum_version] [&afl=fallback_link]

This is suitable if you do not care about using a custom URL link of pretty URLs and having a long URL with parameters is fine.

To create custom domain links you need to register your custom domain on the Firebase console. For iOS additionally you also need to add the following entries to your app Info.plist file

<key>FirebaseDynamicLinksCustomDomains</key>
<array>
  <string>https://myappdomain.com/products</string>
  <string>https://myadddomain.com/articles</string>
</array>

Check out the documentation for creating Setting up Custom Domain Dynamic Links for more information

For detailed information on How to create Firebase Dynamic Links you can refer to the documentation of the Firebase developer documentation on Creating Dynamic Links and Manually Creating Dynamic App Links.

Step 2: Add the Firebase SDK to your respective Android and iOS project

To receive Dynamic App Links in your Android and iOS apps you need to follow the platform specific steps as follows.

Android
  • Add the Firebase SDK in your project using the setup guide.
    Remember to add necessary Firebase dependency in your module level build.gradle file. If you are using Android BoM to declare your dependency then you need not specify the Firebase SDK version, the right compatible version will be automatically imported for you.
dependencies {
  
  // Import the BoM for the Firebase platform
    implementation platform('com.google.firebase:firebase-bom:29.0.3')

    // Declare the dependencies for the Dynamic Links and Analytics libraries
    // When using the BoM, you don't specify versions in Firebase library dependencies
    implementation 'com.google.firebase:firebase-dynamic-links'
    implementation 'com.google.firebase:firebase-analytics'
}
  • Do remember to enable and accept the terms of service for Dynamic Links in your Firebase console
  • Ensure that you have added the SHA256 certificate fingerprint for your app into your project on Firebase
  • Add the intent filter like you do for Native method in your AndroidManifest.xml
<intent-filter>
    <action android:name="android.intent.action.VIEW"/>
    <category android:name="android.intent.category.DEFAULT"/>
    <category android:name="android.intent.category.BROWSABLE"/>
    <data
        android:host="myappdomain.com"
        android:scheme="https"/>
</intent-filter>
iOS
  • You may set up the Firebase SDK for your iOS project either using the Swift Package Manager or using CocoaPods. Refer to the Installation Guide for Apple Apps in the Firebase documentation for details.
  • Add the GoogleService-Info.plist file to the root of your XCode project
  • Next, in the Firebase console, accept the terms of service for Dynamic Links if you haven’t done so already,
  • Ensure your App store ID and App ID are correctly specified in the Firebase App Settings
  • To verify if your iOS app is connected to Firebase successfully to use Dynamic links, launch the following URL
{"applinks":{"apps":[],"details":[{"appID":"1234567890.com.myappdomain.ios","paths":["NOT /_/*","/*"]}]}}

If you app is connected, your apple-app-site-association file will contain a reference to your app’s App ID prefix and bundle ID

Step 3: Handle the Dynamic App Link in you app code

Android
  • Once this is done, you need add the code to handle the Dynamic link in every activity that would be launched at app start as defined in your intent filters
FirebaseDynamicLinks.getInstance()
        .getDynamicLink(getIntent())
        .addOnSuccessListener(this, new OnSuccessListener<PendingDynamicLinkData>() {
            @Override
            public void onSuccess(PendingDynamicLinkData pendingDynamicLinkData) {
                // Get deep link from result (may be null if no link is found)
                Uri deepLink = null;
                if (pendingDynamicLinkData != null) {
                    deepLink = pendingDynamicLinkData.getLink();
                }


                // Handle the deep link. For example, open the linked
                // product page or open user's profile              
            }
        })
        .addOnFailureListener(this, new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.w(TAG, "getDynamicLink:onFailure", e);
            }
        });

If you need more information on Receiving Dynamic App links, refer to Receive Firebase Dynamic Links for Android in the FIrebase documentation

iOS

Once you have your Firebase SDK setup and App association completed with Firebase, you need to setup a few things in your XCode project settings

  • In your XCode Project info tab create a new URL type to be used with Dynamic Links and set the identifier to unique value and URL Scheme your apps bundle Identifier
  • In the Capabilities tab of your app’s Xcode project, enable Associated Domains and add the following to the Associated Domains list:

applinks:your_dynamic_links_domain

  • To handle fully custom domain Dynamic links create a new key in your app’s Info.plist file FirebaseDynamicLinksCustomDomains and set it to your apps Dynamic link prefixes

FirebaseDynamicLinksCustomDomains

https://myappdomain.com/products
https://myappsdomain.com/articles

  • Import the Firebase module in your UIApplicationDelegate Class

Import Firebase

  • Configure an shared instance of FirebaseApp in your application:didFinishLaunchingWithOptions: your

// Use Firebase library to configure APIs
FirebaseApp.configure()
In the application:continueUserActivity:restorationHandler: method handle the link received

func application(_ application: UIApplication, continue userActivity: NSUserActivity,restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
  let handled = DynamicLinks.dynamicLinks()
    .handleUniversalLink(userActivity.webpageURL!) { dynamiclink, error in
      // ...
    }

  return handled
}
  • Lastly application:openURL:sourceApplication:annotation: (iOS 8 and older) and application:openURL:options: (iOS 9 and up) handle links
@available(iOS 9.0, *)
func application(_ app: UIApplication, open url: URL,
                 options: [UIApplication.OpenURLOptionsKey: Any]) -> Bool {
  return application(app, open: url,
                     sourceApplication: options[UIApplication.OpenURLOptionsKey
                       .sourceApplication] as? String,
                     annotation: "")
}

func application(_ application: UIApplication, open url: URL, sourceApplication: String?,
                 annotation: Any) -> Bool {
  if let dynamicLink = DynamicLinks.dynamicLinks().dynamicLink(fromCustomSchemeURL: url) {
    // Handle the deep link. For example, show the deep-linked content or
    // apply a promotional offer to the user's account.
    // ...
    return true
  }
  return false
}

Advantages of using Firebase

Using Firebase has some advantages as opposed to handling Deep links using native methods.

  • Firebase allows you to manage deep links for multiple domain names for Android and iOS in a central place
  • Firebase Dynamic links also work across app installs – which means that if you open a dynamic link and do not have the app for it, it can navigate to the app store, prompt for an update, and then take the user to the newly installed app too with the Dynamic Link still working
  • Firebase also has inbuilt Analytics that allow you to closely monitor your Dynamic Link usage
  • The SDK also allows you to create new Dynamic Links and associate new patterns to be handled programmatically.
  • Firebase Dynamic Links is a free service for any number of links, forever!

Wrapping it up

Deep Links offer a great way to improve the experience for users of your app. It is universally expected that if a user has your app installed, URLs for your service would be handled in the app as it would provide the best experience for the end-user instead of the web link.

Deep Linking is thought to be difficult to implement as there are a number of steps that need to be taken for each platform iOS and Android. This can get overwhelming.

However, implementing Deep Links is simplified using services like Firebase, and taking if your service has use cases that benefit from Deep Link integration, it is definitely worth setting them up.

Do share your feedback and comments on this post. We look forward to bringing you more technology tutorials and programming How-to content in the future. Your feedback is appreciated and will help us get better at sharing useful content for the programming community.

Bitkraft’s Smart WBS Tool

Download this Excel based project management tool that takes a step-by-step approach to complete large projects

Next Step

Contact us if you have any mobile app projects in your mind.

Share your love
Aliasger Rangoonwala
Aliasger Rangoonwala
Articles: 4