Launching apps from the background using React Native deep linking

After enabling deep linking, everything seems to be working fine when the application is opened. However, I've encountered an issue when trying to open the app from a background state using the URL moderatorapp://hello. While it logs the correct URL, the deep linking functionality does not work in this scenario. Below is the code snippet that I am using:

componentDidMount() {
    // Storage.clear();
    Storage.getItem('data_moderator')
        .then(_data => {
            if (_data && _data.tokens) {
                this.autoLogin(_data.tokens);
            } else {
                Actions.loginForm();
            }
        }
    );

    Linking.getInitialURL()
        .then(url => {
            console.log('Initial Url then ', url);
            if (url) {
                console.log('Initial Url ', url);
            }
        })
        .catch(error => console.log(error));

    Linking.addEventListener('url', this.handleOpenURL);
}

The issue seems to be because the componentDidMount method is not being called at that particular point.

Approaches Tried:

I tried wrapping the Linking code inside an event listener that detects when the application enters the active state, but it did not resolve the issue. It still logs the same URL as the initial attempt when the app was closed. Additionally, when attempting to deep link into the app from the background state using the URL moderatorapp://goodbye, it logs the moderatorapp://hello instead of updating as expected.

AppState.addEventListener('change', (state) => {
    if (state === 'active') {
        console.log('state active');
        Linking.getInitialURL()
            .then(url => {
                console.log('Initial Url then ', url);
                if (url) {
                    console.log('Initial Url ', url);
                }
            })
            .catch(error => console.log(error));
    }

    if(state === 'background'){
        console.log('background');
    }
});

As a newcomer to React Native, any guidance on how to address this issue would be highly appreciated.

Thank you.

Answer №1

Visit this link for more information on React Native linking:

- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
   {
return [RCTLinkingManager application:application openURL:url options:options];
}

For those targeting iOS 9 or newer, Apple has changed the API for linking which requires adding this code to your AppDelegate.m file.

Answer №2

The deep linking feature is functioning properly for me even when the application is running in the background. Please review the specifications provided below.

Node Version: v12.18.x OR Higher NPM Version: v6.14.x OR Higher react-native-cli: 2.0.1 react-native: 0.63.x OR Higher

Ensure that you have included the following line in your AppDelegate.m.

#import <React/RCTLinkingManager.h>

This should be added before the #ifdef FB_SONARKIT_ENABLED line. Placing it after this line could cause build failures during Archiving for release.

Verify if the following code snippet is present in your AppDelegate.m file, as it handles deep linking functionality.

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options { return [RCTLinkingManager application:application openURL:url options:options]; }

While this code caters to app cold boot scenarios, additional code needs to be inserted in AppDelegate.m to support deep linking when the app is in the background.

- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(nonnull void (^)(NSArray<id> *_Nullable))restorationHandler { return [RCTLinkingManager application:application continueUserActivity:userActivity restorationHandler:restorationHandler]; }

This implementation should function regardless of whether your app's AppState is: active **OR** background.

I have successfully tested this and it works well! Feel free to give it a try. It should definitely work for you too.

Thank you in advance!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble with clicking a button in HTML?

I'm facing an issue with a button on my HTML page that features a background created using the popular particle library. The button is visible but not clickable. I've attempted adjusting the background size and alignment without success. How can ...

apply a visible border to the item that is clicked or selected by utilizing css and vue

I have a list of items that I want to display as image cards with an active blue border when clicked. Only one item can be selected at a time. Below is the code snippet: Template Code <div class="container"> <div v-for="(obj ...

Using CasperJS, learn how to effectively utilize the jQuery find() function

I'm looking to implement something similar to Cabybara within a function in CasperJS. My goal is to select parent divs and extract text from their child elements. Here's an example of what I want: $('div.education').find('h4&apos ...

The AngularJS framework is not effectively generating the desired table structure

EDIT 1 - Here is a Plnkr example that demonstrates the issue - http://plnkr.co/edit/qQn2K3JtSNoPXs9vI7CK?p=preview ---------------- ORIGINAL CODE AND PROBLEM ---------------- I've been using the angular datatable library (angular-datatables) to g ...

What could be preventing this AJAX call from running correctly?

I am in the process of developing a website that provides users with a discount based on a promotional code they can input. It is important for me to verify the validity of the code in our database before allowing a new sign-up to proceed. Below is the AJA ...

How can async/await help in retrieving the value of a CORS request?

Trying to make a CORS request and utilize async/await to extract the value from it (using jquery). The functions createCORSRequest and executeCORSRequest seem to be functioning correctly, so the implementation details are not my main concern. The function ...

Unexpected behavior encountered when using the $http.post method

I've been working with a component that I utilized to submit data to the Rest API. The code snippet for the component is as follows: (function(angular) { 'use strict'; angular.module('ComponentRelease', ['ServiceR ...

Nested data is the foundation of the Polymer framework's dom-repeat

Struggling with implementing Polymer's <dom-repeat>. Working with parent objects (folders) and child objects (contents within the folders) that are both generated from AJAX responses. The desired output should look like this: Folder child c ...

Turn off the extra space inserted by DataTables

Help needed with centering table header text. <table class="table table-bordered table-hover center-all" id="dataTable"> <thead> <tr> <th scope="col" style="text-align: center">Nam ...

evaluation is not being executed in javascript

I am struggling to assign a value of 1 to the educationflag variable. I am trying to avoid calling the enableEdit.php file when the flag is set to 1. The issue arises when control reaches the if condition but fails to set the variable to 1. Here is my cod ...

JavaScript function is not identifiable

I am currently developing a tic-tac-toe game with 9 buttons that will display either an X or O image depending on the boolean value of the variable isX. The main container for these buttons is a div element with the id 'stage' and each button ha ...

The requested API endpoint for retrieving the name could not be found on the Express

Struggling to configure the restful API for my express app. Below is my app.js code: var express = require('express'), app = express(), bodyParser = require('body-parser'), methodOverride = require('method-override'); rout ...

What is the method for assigning a link to a variable in JavaScript?

As I develop a website featuring an HTML course, I've opted for a consistent format for each lesson or page. One detail I've been working on involves setting a link within a button to a variable enclosed in quotes. For instance, I utilize the cod ...

Preventing default form submission in jQuery: How to cancel it when a certain condition is met

I have a contact form where I validate the input values upon clicking on the submit button. If there is at least one empty input, I trigger an alert and prevent the form submission by using preventDefault. However, if all inputs are filled and submitted, t ...

Ensuring Data Integrity in Angular JS Forms

I've been working on submitting a blank form that triggers custom error messages on mandatory fields. The validation is working perfectly, but I'm running into an issue when the form is loaded for the first time and the user clicks directly on th ...

External JavaScript files are also subject to the same origin policy

Suppose a website http://www.mysite.com contains an external JavaScript file added like this: <script src="http://www.yoursite.com/new.js"></script> Within the http://www.yoursite.com/new.js JavaScript file, there is an AJAX call to a script ...

Prevent JSON-Pretty from being cached for JavaScript files that rely on it

I recently created a Squarespace website using a template that features a unique masonry type gallery layout, which can be viewed at the following link: . Although I was drawn to this template specifically for its gallery design, I've encountered seve ...

Disable default behavior in a SharePoint 2010 List new form with jQuery if conditions are not met

In the SharePoint 2010 List new form, there are 10 checkboxes available. I specifically need to choose exactly 3 of them and not less than that. Even though I implemented jquery for this purpose, it seems that the form does not stop submitting when the con ...

Retrieve the targeted row from the table and then employ a function

Here is a datatable that I am working on: http://jsbin.com/OJAnaji/15/edit I initially populate the table with data and display it. Then, I add a new column called "kontrole." data = google.visualization.arrayToDataTable([ ['Name', &apo ...

What is the best way to remove highlighted text from a textbox that is already selected?

So I have a JS function that I thought was simple, but I'm running into an issue. This function is supposed to select all the text in an ASP.NET textbox (input): function selectAllText(textbox) { textbox.focus(); textbox.select(); } I call t ...