与域名深度链接

问题描述

我的 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>
  );
}

其中大部分是从 https://reactnavigation.org/docs/deep-linking/https://reactnavigation.org/docs/use-linking/ 复制的。

在文档中有 prefixes: ['https://mychat.com','mychat://'],我只是将 https://mychat.com 更改为 http://example.com。但它似乎不起作用。

当我在 Safari 中打开以下链接时:

  • mychat://(有效,被重定向到应用 Screen1
  • mychat://screen-2(有效,被重定向到应用 Screen2
  • http://example.com(只需在浏览器中打开链接,不会弹出重定向到应用程序)

我需要做哪些更改才能将域名重定向到移动应用?我错过了什么吗?

解决方法

您需要使用您有权访问的域以及服务器。

您的服务器需要托管几个文件,通常在 .well-known 目录中:

  • apple-app-site-association(注意不需要 .json
  • assetlinks.json

您还需要在您的应用中为 iOS 启用一些权利,这对于 Android 可能也是如此。在 iOS 上,这将在 webcredentials:yourdomain.com

条目旁边启用 Associated Domains 权利

文档非常好,可以让您了解为了实现通用链接需要做什么

示例: