Step by step guide to setting up Firebase Dynamic Links. 
Tags: reactnative, firebase, linking, tutorial
Published: 2020-06-26 19:04:41

This post covers each step needed to set up firebase dynamic links. As it was really confusing for me to set up and especially making platform-specific changes to codebase. Firstly I will cover ***Firebase dynamic link*** installation-related instructions then will move to Platform(ios/android) specific changes. 

Put on your &nbsp; :headphones: &nbsp;   headphones, turn up the music and just follow each step. :sweat_smile:


##Installation##

1. Firebase Dynamic module requires that the ***@react-native-firebase/app*** module is already setup and installed.```yarn add @react-native-firebase/app```
2. Install the dynamic-links module```yarn add @react-native-firebase/dynamic-links```
3. If you're developing your app: <code>cd ios/ && pod install</code>

---

##Firebase Setup##

1. Go to dynamic links section of your [firebase console](https://console.firebase.google.com/) and configure a new domain for your app. Example- `https://rnfbtestapplication.page.link`
2. Create a dynamic link with your domain. Example- ```https://rnfbtestapplication.page.link/invite/132```
---
##Android Setup##

1. Create a SHA-256 fingerprint using these [instructions](https://developers.google.com/android/guides/client-auth) for your app, and add to your app in your Firebase console.<br>

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/b82mfwq0zd3lktgk26rw.png)<br> 2. Download <code>google-services.json</code> and put it inside your project in <code>./android/app</code> folder.<br><br> 3. Test the domain you created in your Firebase console. Go to the following location in your browser [your-domain]/.well-known/assetlinks.json. 
Example- <code>https://rnfbtestapplication.page.link/.well-known/assetlinks.json. </code><br>
The response will have a target object containing a **package_name** which ought to have your ***app's package name***. Please do not proceed until you see this, it may take a while to register. <br><br>4. Receiving Links:  add a new intent filter to the activity that handles deep links for your app. In your project's <code>AndroidManifest.xml</code> add following <code>intent-filter</code>

```
<intent-filter android:autoVerify="true">
    <action android:name="android.intent.action.VIEW"/>
    <category android:name="android.intent.category.DEFAULT"/>
    <category android:name="android.intent.category.BROWSABLE"/>
    <data android:host="rnfbtestapplication.page.link" android:scheme="http"/>
    <data android:host="rnfbtestapplication.page.link" android:scheme="https"/>
</intent-filter>
```

---

##IOS Setup##

To setup Dynamic Links on iOS, it is a prerequisite that you have an Apple developer account [setup](https://developer.apple.com/programs/enroll/).

1. Add an <code>App Store ID</code> & <code>Team ID</code> to your app in your Firebase console. If you do not have an App Store ID yet, you can put any number in here for now. Your <code>Team ID</code> can be found in your Apple developer console.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/0ru4gpmflue3equxtkcy.png)<br>2. Test the domain you created in your Firebase console, just like you did for android in step 3. Go to the following location in your browser <code>[your domain]/apple-app-site-association</code>,  Example- <code>https://rnfbtestapplication.page.link/apple-app-site-association</code>. The response will have a details array property containing an object that has the property <code>appID</code>. That will be your app's app ID (It may take some time for your domain to register). Please ensure it is registered before proceeding.<br><br> 3. Once you're sure your domain is registered, you need to head over to your <code>Apple developer console</code> and create a **provisioning profile** for your app. Please ensure you've enabled the **Associated Domain capability** which you should check before proceeding. <br>
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/m6s4pf8gwuz4f8c51g2c.png)<br>4. Receiving Link: <br>
- Open your project in Xcode and open your app under the ```TARGETS``` header. Click the ```Signing & Capabilities``` tab. You will need to ensure your Team is registered, and your Provisioning Profile field is completed. Add the domain you created in your Firebase console to the ```Associated Domains``` and prefix with ```applinks:```

Example: <code>applinks:rnfbtestapplication.page.link</code>

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/kg0jzg02w0pqrlfwf5dr.png)

- Click the ```Info tab```, and add a ```URL Type``` to your project. Add your bundle id to ```URL SCHEMES``` and write ```BundleID``` in ```identifier``` field. 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/qaxidkra4xhrn65tb9pb.png)

- In ```AppDelegate.m``` file in ```application:continueUserActivity:restorationHandler```: method, handle links received as Universal Links when the app is already installed.

```
- (BOOL)application:(UIApplication *)application
continueUserActivity:(nonnull NSUserActivity *)userActivity
 restorationHandler: 
#if defined(__IPHONE_12_0) && (__IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_12_0)
(nonnull void (^)(NSArray<id<UIUserActivityRestoring>> *_Nullable))restorationHandler {
#else
    (nonnull void (^)(NSArray *_Nullable))restorationHandler {
#endif  // __IPHONE_12_0
  BOOL handled = [[FIRDynamicLinks dynamicLinks] handleUniversalLink:userActivity.webpageURL
                                                          completion:^(FIRDynamicLink * _Nullable dynamicLink,
                                                                       NSError * _Nullable error) {
                                                            // ...
                                                          }];
  return handled;
}

```

This is it for native changes required for ios and android. Now we will be using firebase dynamic links api to create dynamic links and adding listeners to receive and handle those links. 

---

##Create a Link##

```javascript
import dynamicLinks from '@react-native-firebase/dynamic-links';

async function buildLink() {
  const link = await dynamicLinks().buildLink({
    link: 'https://invertase.io',
    // domainUriPrefix is created in your Firebase console
    domainUriPrefix: 'https://xyz.page.link',
    // optional set up which updates Firebase analytics campaign
    // "banner". This also needs setting up before hand
    analytics: {
      campaign: 'banner',
    },
  });

  return link;
}
```
---
##Listening for Dynamic Links##

```javascript
//  firebase dynamic linking listener
  useEffect(() => {
    dynamicLinks()
      .getInitialLink()
      .then((link) => {
        handleDynamicLink(link);
      });
    const linkingListener = dynamicLinks().onLink(handleDynamicLink);
    return () => {
      linkingListener();
    };
  }, []);
```
  

```javascript
  function handleDynamicLink(link) {
    console.log(link);
}
```