Categories: Blog

Firebase Dynamic Links

Deep links are a powerful and essential part of a market’s toolkit. They are connecting users to campaigns, streamlining user experience and exposing users to the right marking.

Many developers are using traditional ways of Deep links in their app. It’s required to add below link of code in website or any link header part.


setTimeout(function () { 
          window.location = "https://itunes.apple.com/appname"; },25); 
window.location = "appname://";

These lines will check if the app is installed then it will open the app. If the app is not installed, then it will show the Install button on top of your web page. Tapping on that, it will redirect to Apple/Google Store. From this url, developers are appending their required parameters and fetching those parameters from the app and then writing redirection code in the app. But it’s a very tedious task for a web team.

Fortunately, Firebase has released DynamicsLinks. Firebase Dynamic Links also work in the same convenient way. But the only difference is, in the traditional way, we are not able to get deep links data if the app is not installed and then we install it. But in Firebase Dynamic links, we will be able to get deep kinks links data even after installing a new build. A single link will work in all platforms. Means, if links are shared to iOS, Android or Web, it will show content to the users.

How does it work?

A link can be created using Firebase Console, REST API or Android or iOS Builder or just adding Dynamic Link parameters to a domain specific to your app. These parameters specify the links you want to open and redirection and whether the app is installed or not.

Set up Firebase and the Dynamic Links SDK

Many of us know how to set up Firebase using Pods. If anyone is new here, go through this link. To set up Dynamic links, install pod ‘Firebase/DynamicLinks’. Also, please download the latest ‘GoogleServices-Info.plist’ file and place it in your project root directory.

Go to the Dynamic Links section from the left side Firebase Console page. It will show the kind of page below

Tap on Get Started and it will show one pop up as below:

This will show you some predefined domain names which you can select. You can also write the name which you want. After selecting the domain name, tap on the ‘Continue’ button.

In the next step, it will check the name which you have entered or selected is valid or not, if it’s valid, it will redirect us to step 4.

Here, we have completed setting up the Domain host for Firebase Deep Links. You can test your domain name in the browser as well.

Next step is to verify whether associated domains are opened for deep links or not, and that is we will check with the traditional Apple way. For more details about Apple Universal links, visit here.

Go to Apple Developer web page, select your App Identifier, and check whether Associated Domains is selected or not. If not selected, select it and save. Update your provisioning profiles as well after this modification.

Next step is to turn ON the same in your App Target as well. So, go to xcode and select app from target, move to Capability section. Add new Capability as ‘Associated Domain’. Add your Firebase Deep Link domain name appending by ‘applinks:’ work. Same as attached image.

Upto so now, we did just basic setup in Firebase Deep link and xcode capability. Now, to verify whether an associated domain name is properly configured with our app not, we can just simply call Firebase deep link domain name appended by ‘apple-app-site-association’ word and check in the browser.

https://example.page.link/apple-app-site-association

This link will below kind of response in a web browser.


 {
	applinks: 
	{
		apps: [ ],
		details: 
		[
			{
				appID: "7CN7W3WLZT.com.letsnurture.Demo1",
				paths: 
				[
					"NOT /_/*",
					"/*"
				]
			},
			{
				appID: "82VM7VB8H2.com.app.demo2",
				paths: 
				[
					"NOT /_/*",
					"/*"
				]
			}
		]
	}
}

If this link shows your app bundle identifier, that means you have properly configured all stuff.

How to create Firebase Deep Links url from iOS app?

Firebase Deep Link can be created either short url or long url. These urls you can share with your friends, marketing campaigns, promotional offers. When a user taps on this kind of link, it will launch the app if the app is already installed on your phone. If the app is not installed, then it will redirect to Stores, and from there the user can download the app.

To create these kinds of links, you need to add the first Firebase domain name in Info.plist file. Check attached image.

Also, I need to set up in the URL Types section. Add a new section as setup as below.

Now, the next part is to write code to generate long and short urls.


func generateDynamicShareLink(_ mediaURL: URL, completion: @escaping ((_ shareUrl : String) -> ())){
    guard let longShareLink = DynamicLinkComponents.init(link: mediaURL, domainURIPrefix: "https://starmanch.page.link") else { return }
    
    if let bundleID = Bundle.main.bundleIdentifier {//This will get an iOS app bundleID and set in iOSParameter. You can also set Android bundle id here.
        longShareLink.iOSParameters = DynamicLinkIOSParameters(bundleID: bundleID)
        longShareLink.androidParameters = DynamicLinkAndroidParameters(packageName: bundleID)
        //TODO: Set correct App store ID, currently set GMail app id.
        longShareLink.iOSParameters?.appStoreID = "1234567890"
        longShareLink.socialMetaTagParameters = DynamicLinkSocialMetaTagParameters()
        longShareLink.socialMetaTagParameters?.title = "My App"
        longShareLink.socialMetaTagParameters?.descriptionText = "Wow!! Check out cool app. You can add app description here."
        longShareLink.socialMetaTagParameters?.imageURL = URL(string: "http://www.myserver.com/images/logo.png")
    }
    
    guard let longDynamicLink = longShareLink.url else { return }
    print("The long URL is: \(longDynamicLink)")
    
    DynamicLinkComponents.shortenURL(longDynamicLink, options: nil) { (url, warnings, error) in
        if let shortURL = url {
            print(shortURL)
            completion(shortURL.absoluteString)
        }
    }
}

This block will accept your server share page url and generate a short Firebase deep link and return short url back.

For example, if we pass server url as https://www.example.page.link/share?id=23 then, above function will return this kind of url. https://example.page.link/qweqesdasdasd. For the same share url, deep links url will be unique.

Now, we can share this url to any user by presenting UIActivityViewController and selecting any social media sharing option.

When another user receives this url and tap on link, app will check in below method in SceneDelegate.swift file.


func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {
        if let incomingURL = userActivity.webpageURL{
            print("incomingURL is \(incomingURL)")
            let _ = DynamicLinks.dynamicLinks().handleUniversalLink(incomingURL) { (dynamicLink, error) in
                guard error == nil else {
                    print("Found an error \(error!.localizedDescription)")
                    return
                }
                if let dynamicLink = dynamicLink{
                    self.handleIncomingDynamicLink(dynamicLink)
                }
            }
        }
    }

func handleIncomingDynamicLink(_ dynamicLink: DynamicLink){
        guard let url = dynamicLink.url else {
            print("Dynamic link as no any url")
            return
        }
        print("Dynamic link parameters \(url.absoluteString)")
        
        guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false), let queryItems = components.queryItems else {
            return
        }
        
        //TODO: Set redirection code here for DeepLinks
        if components.path == "/share" {
            for queryItem in queryItems{
                print("Parameter has value \(queryItem.value)")
                if queryItem.name != "id" {
                    sharedId = queryItem.value ?? ""
                }
            }
        }
    }

This will call the below methods in the AppDelegate.swift file.


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) {
//            delay(7.0) {
//                showAlert("Open URL Called :-> \(dynamicLink)")
//            }
            self.handleIncomingDynamicLink(dynamicLink)
            return true
        }
        return true
    }

// MARK: - Linking delegate methods

    func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
        if let incomingURL = userActivity.webpageURL{
            print("incomingURL is \(incomingURL)")
            let linkHandled = DynamicLinks.dynamicLinks().handleUniversalLink(incomingURL) { (dynamicLink, error) in
                guard error == nil else {
                    print("Found an error \(error!.localizedDescription)")
                    return
                }
                if let dynamicLink = dynamicLink{
                    self.handleIncomingDynamicLink(dynamicLink)
                }
            }
            if linkHandled {
                return true
            } else {
                return false
            }
        }
        return true
        //        return UIApplication.shared.application(application, continue: userActivity, restorationHandler: restorationHandler)
    }
    

 func handleIncomingDynamicLink(_ dynamicLink: DynamicLink){
        guard let url = dynamicLink.url else {
            print("Dynamic link as no any url")
            return
        }
        print("Dynamic link parameters \(url.absoluteString)")
        
        guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false), let queryItems = components.queryItems else {
            return
        }
        for queryItem in queryItems{
            print("Parameter \(queryItem.name) has a value of \(queryItem.value ?? "")")
            
        }
        //TODO: Set redirection code here for DeepLinks
    }

These all are parsing methods to parse Firebase Deep Link urls with parameters. Based on parameters received, you can redirect url to respective screens.

Conclusion

Apple’s traditional Associated domain is very tedious and all these setups on the web are very complex. Firebase Deep Links come up with a very easy and effortless way for deep link and its redirection. Also, it’s very easy for developers to set up and redirection. Firebase helps you develop high-quality mobile apps, grow your user base and boost-up the business. Each feature works independently, and they work even better together.

To know more about how Firebase helps in developing high quality app, please get in touch with us

Lets Nurture

Share
Published by
Lets Nurture

Recent Posts

7 Powerful Psychological Triggers to Skyrocket Your Website Engagement

In the digital age, understanding the hidden forces driving user behavior is essential. By strategically…

8 months ago

What is haptics? How can we implement in in AR based mobile App? What are Haptics Use cases?

What is haptics?   Haptics refers to the use of touch feedback technology to simulate…

11 months ago

The Benefits of Using Virtual Reality in Business

In today's fast-paced and technologically driven world, businesses are constantly seeking innovative ways to stay…

1 year ago

A Closer Look at New Jersey’s Thriving Incubator Ecosystem

The Garden State, more popularly known as New Jersey, is not only known for its…

1 year ago

Why You Need a Mobile App for Your Business

In today's digital age, mobile apps have become an indispensable tool for businesses across all…

1 year ago

How to Optimize Your Website for Better User Experience

In today's digital era, a seamless and enjoyable user experience is crucial for the success…

1 year ago