Firebase Dynamic Links in iOS (Programmatically)
Published: 2020-04-30 21:06:11

In this article, we will discuss how to create a dynamic link in iOS programmatically.

## Let's get started:
   We will continue from our previous article if you miss that you can read it [here](https://medium.com/p/847a5984acd9) in which we discuss what is firebase and how to set it up.
So let's get started first we will install firebase pods to access the dynamic link features. open podfile and add this pod in it. If you don't know how to create a podfile follow this [link](https://guides.cocoapods.org/using/using-cocoapods.html) it will help you.
```
pod 'Firebase/DynamicLinks'
```
Open AppDelegate in your project and in method **didFinishLaunchingWithOptions** write
```
FirebaseApp.configure()
```
Ensure that your app's App Store ID and your App ID prefix is specified in your F[irebase app's settings](https://console.firebase.google.com/project/_/settings/general/).

The dynamic link is an embedded link with a URL and query parameters that are used for redirection. First, we will create URLComponents, dynamic link use this link for redirection when it open in a browser.
```
var components = URLComponents()
components.scheme = "https"
components.host = "medium.com"
components.path = "/userID"
```
Now we will create **URLQueryItem** and add it into the components which we create earlier. Currently, I am using a random key(id) but you can change it and give appropriate value to it so when it hit then it will perform the same action as you wanted like if you want to share some content of the application use its id here because this id is fetched when this link opens the application.
```
let queryItem = URLQueryItem(name: "id", value: id)
components.queryItems = [queryItem]
```
Now create a **DynamicLinkComponents** this is a long shareable link. It took two params:
1. URL
2. Dynamic link prefix.
  From the component that we just created, we will get the URL and the prefix is that which we created on the Firebase Console.
  ```
guard let urlComponent = components.url else { return nil }
guard let longShareLink = DynamicLinkComponents.init(link: linkParameter, domainURIPrefix: "appnamee.page.link") else { return nil }
```
Now we will add iOS and Android parameters to the created share link.
**Note:** Change bundle ID for Android if you are using different otherwise use the same way. Change the AppStoreID so the app will redirect to your app on the store.
```
if let bundleID = Bundle.main.bundleIdentifier {
    longShareLink = DynamicLinkIOSParameters(bundleID: bundleID)
    longShareLink.iOSParameters?.appStoreID = "AppStoreID"
    longShareLink.iOSParameters.minimumAppVersion = "1.0"
longShareLink.androidParameters = DynamicLinkAndroidParameters(packageName: bundleID)
    longShareLink.androidParameters.minimumVersion = 1.0
}
```
You can also add social tags to the link like if you want to show add or any promotion or some content. This will show when the app is not installed and firebase will create a web URL for you and it will show there.
```
longShareLink.socialMetaTagParameters = DynamicLinkSocialMetaTagParameters()
longShareLink.socialMetaTagParameters?.title = "Title Of Promotion"
longShareLink.socialMetaTagParameters?.descriptionText = "Description Of Promotion"
longShareLink.socialMetaTagParameters?.imageURL = URL(string: "ImageURL")
```
The web page will be like this
![WebView](https://ucarecdn.com/22275f3b-6082-4257-b1ce-d289fe97b189/)
Now we will shorten that URL to share it because we cant share a long link.
```
guard let longURL = longShareLink.url else { return nil }
DynamicLinkComponents.shortenURL(longURL!, options: nil) { (url, warnings, error) in
   if let shortURL = url {
       print(shortURL)
    }
}
```


![Tada](https://cdn-images-1.medium.com/max/1600/1*fczPwDwUDpblR-wKP-kMeQ.gif)

## Receive Dynamic Links
Now we will configure and write some code that how code will react when it receives Dynamic link. Let's get started

## Configuration
First, we will enable **Associated Domain** capability in identifiers. For that Follow these steps:
1. Login in [Apple Developer Account](https://developer.apple.com/account/).
2. Goto Certificates, Identifiers & Profiles.
3. Select Identifiers.
4. Open the identifier of your application.
5. Mark the Associated Domains.
6. Then save it.

We are done here now we will configure our dynamic link in our project.
1. Open Project and select target then go to Signing & capabilities.
2. Add capability **Associated Domains**.
3. Now add Domain like this applinks:appnamee.page.link
![Associated Domains](https://ucarecdn.com/ff2757e2-d8a7-4d58-b59b-19ee6be826e7/)

It's Time for some code. if you configure the Firebase then its ok but if u didn't then configure it in AppDelegate.
```
FirebaseApp.configure()
```
when an external URL is hit and it configure in App then **application:openURL:options:** is being called in AppDelegate.
```
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
     let dynamicLink = DynamicLinks.dynamicLinks().dynamicLink(fromCustomSchemeURL: url)
     if dynamicLink != nil {
          print("Dynamic link : \(String(describing: dynamicLink?.url))")
          return true
     }
     return false
}
```
And after that **application:continueUserActivity:restorationHandler:** is called in which we will handle our data
```
func application(_ application: UIApplication, continue userActivity:
NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
     guard let inCommingURL = userActivity.webpageURL else { return false }
     print("Incomming Web Page URL: \(inCommingURL)")
     shareLinkHandling(inCommingURL)
     return true
}
```
For me I usually break down the code into functions so every function has limit lines of codes and easy to handle so we will handle our deep link scenario in **shareLinkHandling** method:
```
fileprivate func shareLinkHandling(_ inCommingURL: URL) {
   
   _ = DynamicLinks.dynamicLinks().handleUniversalLink(inCommingURL) { (dynamiclink, error) in
       
      guard error == nil else {
      print("Found an error: \(error?.localizedDescription ?? "")")
      return
      }
      print("Dynamic link : \(String(describing: dynamiclink?.url))")
      let path = dynamiclink?.url?.path
      var id = 0
      if let query = dynamiclink?.url?.query {
          let dataArray = query.components(separatedBy: "=")
          id = Int(dataArray[1]) ?? 0
      }
     if path == "userID" {
         //Write code here
     } 
   }
}
```
We are done here from creating a Dynamic link to handling it when receiving in code.
![End](https://cdn-images-1.medium.com/max/1600/1*ZLronSWbmj4IwGoWepecHQ.gif)