通過react-navigation設(shè)置打開APP的scheme
react-navigation官網(wǎng)(不知道什么時(shí)候更新了,我還在用1.5.11)[https://reactnavigation.org/docs/en/deep-linking.html]
一、ios
1. 設(shè)置path
(通過如path:"Complaint",則啟動(dòng)的時(shí)候是:你的scheme://Complaint)
配置path(具體語法可以參考官網(wǎng)):
const RouteConfigs = {
Complaint: {
screen: Complaint,//投訴
path: 'Complaint',
}
}
2. 設(shè)置URI Prefix
在react-navigation 入口處添加下面內(nèi)容:
import {Platform} from "react-native";
const prefix = Platform.OS == 'android' ? 'mychat://mychat/' : 'mychat://';
//...others code
// 我的是在根目錄下的app.js,<App/> 是我的入口
<App uriPrefix={prefix} />
3. 在xcode中打開AppDelegate.m文件,如下圖:

AppDelegate.m
#import "AppDelegate.h"
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
// 在這里添加這句
#import <React/RCTLinkingManager.h>
@implementation AppDelegate
//省略其他的代碼
// 在@end前臺(tái)添加上下面這段
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
return [RCTLinkingManager application:application openURL:url
sourceApplication:sourceApplication annotation:annotation];
}
@end

按照?qǐng)D片上的修改
4. 直接在模擬器上測(cè)試
-
react-native run-ios; - xcrun simctl openurl booted zhlx://Complaint
輸入內(nèi)容回車即可:

image.png
二、Android
1. 對(duì)于Android的話,和ios有點(diǎn)不太一樣,就是需要設(shè)置host,通過在APP入口文件添加的
const prefix = Platform.OS == 'android' ? 'mychat://mychat/' : 'mychat://';
有童鞋就已經(jīng)猜出來了。
2. android/app/src/main/AndroidManifest.xml中添加intent-filter;
個(gè)人不懂Android(web前端),所以在使用的時(shí)候遇到了個(gè)坑,如下所示,我將官網(wǎng)讓放的
intent-filter放到了一個(gè)intent-filter里面(示例1),結(jié)果運(yùn)行打包什么的都沒問題,但是打包成apk安裝到手機(jī)后才發(fā)現(xiàn)APP的icon沒了,桌面找不到,只能在設(shè)置里面看到,改為(示例2)后才正確使用。
示例1:
<intent-filter>
<!--這里是原來就有的-->
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
<!--這里是react-navigation 讓添加的-->
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data android:scheme="mychat" android:host="mychat"/>
</intent-filter>
示例2:
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<intent-filter>
<!-- 這里添加 -->
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data android:scheme="mychat" android:host="mychat"/>
<!-- 這里結(jié)束 -->
</intent-filter>
官網(wǎng)截圖:

官網(wǎng)截圖
3.運(yùn)行程序測(cè)試
- 運(yùn)行
react-native run-android adb shell am start -W -a android.intent.action.VIEW -d "mychat://mychat/chat/Eric" com.simpleapp
mychat://mychat/chat/Eric 就是在瀏覽器或者其他外部打開并跳轉(zhuǎn)到APP的鏈接;
大家可以對(duì)比參考ios和Android的scheme:
- ios:mychat://chat/Eric
- android :mychat://mychat/chat/Eric
end !