- 版本:2.0.0
- GitHub: https://github.com/sebestindragos/nativescript-plugin-universal-links
- NPM: https://npmjs.net.cn/package/nativescript-plugin-universal-links
- 下载
- 前一天:0
- 上周:0
- 上个月:0
NativeScript Universal Links 插件
为 NativeScript 应用提供通用链接(iOS)和应用链接(Android)支持。
当用户点击指向网站的链接时,它会在默认网页浏览器(Safari/Chrome)中打开。通用链接允许您的应用打开而不是网页浏览器。
苹果将其称为通用链接,而谷歌称为应用链接,但它们意味着相同的事情。
使用以下命令安装此插件:npm install nativescript-plugin-universal-links
实现通用链接
iOS(9.0及更高版本)和Android(所有版本)都为通用链接提供了良好的API。
iOS
苹果在iOS 9.0中引入了一个名为“通用链接”的新深链接API。它比iOS 8.0及以下版本中存在的漏洞式深链接选项提供了更好的用户体验。
第一步是在您的网站根目录中添加一个名为apple-app-site-association
的文件。这是一个JSON文件,其外观如下
{
"applinks": {
"apps": [],
"details": [
{
"appID": "your-team-id.com.example",
"paths": [ "/blog/*"]
}
]
}
}
- 此文件将由安装或升级您的iOS应用的每个用户自动下载。
- 它必须通过HTTPS和有效的SSL证书提供服务。如果您需要测试此内容,我建议使用https://ngrok.io
- 因为此文件仅在用户首次安装或升级应用时获取一次,所以在此应用发布之前,此文件必须存在于您的网站上。这也意味着,您无法在推送新应用更新以强制用户刷新文件之前,将新的深链接URL模式添加到应用中。
有关更多信息,请参阅苹果的文档。
接下来,您需要将关联域添加到您的iOS项目中,可以使用XCode或手动将以下代码添加到您的App_Resources/IOS/app.entitlements
文件中。请注意applinks:
前缀,没有它将无法工作。
<key>com.apple.developer.associated-domains</key>
<array>
<string>applinks:www.example.com</string>
</array>
Android
在Android中,通用链接通过Intent Filters实现。通过添加一个BROWSABLE intent filter,您表示您的应用可以通过用户点击网站URL来启动。
您不需要对Android进行任何服务器端更改,只需修改您的应用以添加Intent Filter。将以下代码添加到您的App_Resources/Android/src/main/AndroidManifest.xml
文件中
<activity
android:name="com.tns.NativeScriptActivity"
android:label="@string/title_activity_kimera" >
<!-- Add this new section to your Activity -->
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<!-- Handle urls starting with "https://www.example.com/blog" -->
<data android:scheme="https"
android:host="www.example.com"
android:pathPrefix="/blog" />
</intent-filter>
</activity>
使用插件
在AppComponent的ngOnInit方法中调用registerUniversalLinkCallback
,以提供一个回调方法,每次应用通过网站链接打开时,都会接收一个通用链接对象。
import { Component, OnInit } from "@angular/core";
import { registerUniversalLinkCallback } from "nativescript-plugin-universal-links";
@Component({
selector: "my-app",
template: "<page-router-outlet></page-router-outlet>"
})
export class AppComponent {
constructor() {}
ngOnInit() {
registerUniversalLinkCallback(ul => {
// use the router to navigate to the screen
});
}
}
通用链接对象具有以下结构
{
"href": "https://www.example.com/blog?title=welcome",
"origin": "https://www.example.com",
"pathname": "/blog",
"query": "?title=welcome"
}
还有一个getUniversalLink()
方法,将返回打开应用的最后一个通用链接。这在应用受登录屏幕保护的情况下很有用。检查用户是否已认证,然后导航到所需的路径。
import { getUniversalLink } from "nativescript-plugin-universal-links";
const ul = getUniversalLink();