Search code examples
iosreact-nativereact-navigationdeep-linking

Deeplinking with a domain name


I have the following code in my App.js:

import React, { useState, useRef, useEffect } from 'react';
import { SafeAreaView, Text } from 'react-native';
import { NavigationContainer, useLinking } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

const Stack = createStackNavigator();
const Screen1 = () => <SafeAreaView><Text>Screen1</Text></SafeAreaView>;
const Screen2 = () => <SafeAreaView><Text>Screen2</Text></SafeAreaView>;

export default function App() {
  const ref = useRef();
  const [isReady, setIsReady] = useState(false);
  const [initialState, setInitialState] = useState();
  const { getInitialState } = useLinking(ref, {
    prefixes: ['http://example.com', 'mychat://'],
    config: {
      screens: {
        Screen2: 'screen-2',
      },
    },
  });

  useEffect(() => {
    getInitialState().then((state) => {
      if (state !== undefined) setInitialState(state);

      setIsReady(true);
    });
  }, [getInitialState]);

  if (!isReady) return null;

  return (
    <NavigationContainer ref={ref} initialState={initialState}>
      <Stack.Navigator>
        <Stack.Screen name='Screen1' component={Screen1} />
        <Stack.Screen name='Screen2' component={Screen2} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

Most of them are copied from https://reactnavigation.org/docs/deep-linking/ and https://reactnavigation.org/docs/use-linking/.

In the docs there is prefixes: ['https://mychat.com', 'mychat://'], I just changed https://mychat.com to http://example.com. But it doesn't seem to work.

When I open the following links in Safari:

  • mychat:// (works, gets redirected to app Screen1)
  • mychat://screen-2 (works, gets redirected to app Screen2)
  • http://example.com (just opens the link in the browser, no popup to redirect to app)

What change do I need to make to redirect the domain name to the mobile app? Am I missing something?


Solution

  • You need to use a domain that you have access to alongside a server.

    Your server needs to host a couple of files, typically within the .well-known directory:

    • apple-app-site-association (note the .json is not needed)
    • assetlinks.json

    You also need to enable some entitlements within your app for iOS, this may also be true for Android. On iOS, this will be enabling the Associated Domains entitlement alongside an entry for webcredentials:yourdomain.com

    The documentation is pretty good to go through to give an understanding on what needs to be done in order to achieve Universal Links

    Examples: