-
Notifications
You must be signed in to change notification settings - Fork 1
Open
Description
需求描述
新需求需要 App 能让第三方唤起并带数据进入指定页面,类似于分享链接,点击链接跳转到一个中间网页,再从中间页唤起 App 到指定的分享内容页这样的功能。首先要解决的两个问题怎么唤起 App和 App 内怎么接受传入的参数。
实现
唤起App配置
- IOS
在 Project -> Targets -> info -> URL Types 中新增一个 URL Type,填入 Identifier 和 URL Schemes,URL Schemes 相当于 App 的 URL,用来唤起 App。
然后在 AppDelegate.m 中增加以下代码来监听传入的 App 链接:
// iOS 9.x 或更高版本
#import <React/RCTLinkingManager.h>
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
return [RCTLinkingManager application:application openURL:url options:options];
}
// iOS 8.x 或更低版本
#import <React/RCTLinkingManager.h>
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
return [RCTLinkingManager application:application openURL:url
sourceApplication:sourceApplication annotation:annotation];
}
- Android
在 AndroidManifest.xml 中配置 intent-fllter 就可以了
<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="appTest" android:host="appTest" />
</intent-filter>
获取传入的 App 链接
使用 ReactNative 提供的 Linking 模块 可以很方便的获取传入的 App 链接,并且可以打开一个外部链接(浏览器、邮箱或者其它的应用)。使用:
componentDidMount() {
Linking.getInitialURL().then((url) => {
if (url) {
console.log('Initial url is: ' + url);
}
}).catch(err => console.error('An error occurred', err));
}
并添加一个监听 Linking 变化的事件:
Linking.addEventListener('url', (event) => { console.log('url: ', event.url) })
这样外部使用 appTest://appTest/index(Android) 或 appTest://index(ios) 这样的 url 就可以唤起 App 了
总结
主要知识点是 URL Schemes 的运用,配置并不复杂,关于 URL Schemes 的介绍这篇文章很详细,点这里
proyuli
Metadata
Metadata
Assignees
Labels
No labels