在Ionic專案開發程序中,有時候會對其他app專案進行互動的,
本文目的是使用url scheme解決下面2種場景:
- 通過ionic應用喚醒并傳參給第三方的app如淘寶如微信等,
- 或者第三方app或者基本ionic開發的app,喚醒自己開發的ionic應用
場景1
方法1:通過ionic應用喚醒并傳參給第三方的app,如淘寶、微信、ionic應用等
首先定義2個APP
- 自己的應用:APP-MyApp
- 其他的應用:APP-OtherApp
// 安裝相關插件 ionic cordova plugin add com.lampa.startapp
// cordova-plugin-inappbrowser
// cordova-plugin-appavailability
constructor(
private platform: Platform,
private iab: InAppBrowser,
private appAvailability: AppAvailability,
){}
// 喚醒并傳參給第三方的app步驟
handleClick() {
// 1. 首先使用 appAvailability檢查是否存在 目標APP
// 代碼略...
// 2. 如果存在目標APP,呼叫 iab/startApp進行url scheme喚醒
this.openOtherAppByUriScheme(url)
}
/**
* 通過uri scheme打開其他應用app
* @param uriScheme uriScheme 喚醒的uri 如:taobao://item.taobao.com/item.htm?id=603056997271 或者 mydemoapp://abcde?id=603056&cd=en
*/
openOtherAppByUriScheme(uriScheme: string, originParams?: any) {
if (this.platform.is('ios')) {
// ios應用喚醒其他app,切記在plist加上該應用的scheme白名單如 taobao
this.iab.create(uriScheme, '_system');
} else if (this.platform.is('android')) {
// 通過scheme打開app
let sApp = startApp.set({
"uri": uriScheme
}).start();
}
}
方法2:通過ionic應用喚醒并傳參給第三方的app的第二種方法
- 在config.xml中增加第三方app的scheme,如
<allow-intent href="taobao:*" />
<allow-intent href="mydemoapp:*" />
- 在html頁面中直接使用a標簽進行跳轉
<a href="taobao://item.taobao.com/item.htm?id=603056997271"> 打開淘寶app并跳轉到指定商品</a>
// 打開一個測驗app并傳遞下面引數`TB1qimQIpXXXXXbXFXXSutbFXXX?id=603056&cd=en`
<a href="mydemoapp://TB1qimQIpXXXXXbXFXXSutbFXXX?id=603056&cd=en"> 打開另一個App,該App的scheme為mydemoapp</a>
場景2
被其他app以url scheme的方式喚醒自己的ionic應用
// 安裝相關插件,定義自己的app scheme為: myapp://
// ionic cordova plugin add cordova-plugin-customurlscheme --variable URL_SCHEME=myapp
- 找到ionic專案中的app.component.ts,加上以下代碼
constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen) {
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
statusBar.styleDefault();
splashScreen.hide();
// 用于接收url scheme傳入的url和引數
(window as any).handleOpenURL = (url: string) => {
setTimeout(() => {
this.handleOpenUrl(url);
}, 0);
};
});
}
/**
* 處理url scheme 的引數
* @param url urlscheme 鏈接引數,如 guangxidemo://abcde?id=603056&cd=en
*/
private handleOpenUrl(url: string) {
console.log('url', url);
alert(url)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/241867.html
標籤:其他
