Linking提供了一個(gè)通用的接口來與傳入和傳出的 App 鏈接進(jìn)行交互
背景
- 官方文檔
- 在App開發(fā)中我們經(jīng)常會(huì)用到Linking跳轉(zhuǎn)退渗,如:跳轉(zhuǎn)應(yīng)用市場(chǎng),撥打手機(jī)號(hào),打開微信等等送丰。
- 下面針對(duì)這些需求進(jìn)行了基本的封裝怒详。
跳轉(zhuǎn)App應(yīng)用市場(chǎng)
/**
* app應(yīng)用市場(chǎng)下載
* iOS: itms-apps://itunes.apple.com/cn/app/ +【名稱】/【id + id編號(hào)】 如:itms-apps://itunes.apple.com/cn/app/wei-xin/id414478124
* android: market://details?id= + 【app 包名】 如: market://details?id=com.tencent.mm
* @param {*} address 下載地址
*/
export const openMarket = ({ androidAddress = '', iOSAddress = '' }) => {
const linkingUrl = Platform.OS === 'ios' ? `itms-apps://itunes.apple.com/cn/app/${iOSAddress}` : `market://details?id=${androidAddress}`
Linking.canOpenURL(linkingUrl).then(async supported => {
if (supported) {
Linking.openURL(linkingUrl)
} else {
Toast.show('找不到可提供下載的應(yīng)用市場(chǎng)')
}
})
}
撥打手機(jī)號(hào)
/**
* 撥打手機(jī)
* @param {*} tel 手機(jī)號(hào)
*/
export const openTel = (tel) => {
Linking.canOpenURL(`tel:${tel}`).then(async supported => {
if (supported) {
Linking.openURL(`tel:${tel}`)
} else {
await Clipboard.setString(tel)
Toast.show('您的設(shè)備不支持,已為您復(fù)制手機(jī)號(hào)烙懦!')
}
})
}
打開微信
export const openWechat = () => {
Linking.canOpenURL('weixin://').then(supported => {
if (supported) {
Linking.openURL('weixin://')
} else {
Alert.alert('沒有安裝微信',
'請(qǐng)先安裝微信客戶端再打開',
[
{ text: '取消' },
{ text: '安裝',
onPress: () => {
openMarket({
androidAddress: 'com.tencent.mm',
iOSAddress: 'wei-xin/id414478124'
})
} }
])
}
})
}
瀏覽器打開鏈接
/**
* 打開瀏覽器
* @param {*} url url地址
*/
export const openWebBrowser = (url) => {
Linking.canOpenURL(url).then(supported => {
if (supported) {
Linking.openURL(url)
} else {
Toast.show('找不到可以打開的瀏覽器')
}
})
}
React Navigation深度鏈接
- 結(jié)合React Navigation我們可以打開App并跳轉(zhuǎn)到App任何界面
- 應(yīng)用場(chǎng)景:用戶點(diǎn)擊推送消息驱入,打開App并跳轉(zhuǎn)到消息詳情界面。
- 假設(shè)App中我們有OrderDetailScreen這個(gè)界面氯析,router配置如下:
const mainNavigator = createStackNavigator({
....
order_detail: {
screen: OrderDetailScreen,
path: 'order_detail'
}
....
- 我們可以使用以下命令跳轉(zhuǎn)到詳情頁面
return Linking.canOpenURL('myapp://main/order_detail').then(supported => {
if (!supported) {
console.log('Can\'t handle url: myapp://main/order_detail')
} else {
return Linking.openURL('myapp://main/order_detail/' + data.money)
}
}).catch(err => console.error('An error occurred', err))
- 具體配置可以查看 React Navigation文檔
常用URL Scheme
/**
一亏较、常用URL Scheme
QQ: mqq://
微信: weixin://
新浪微博: weibo:// (sinaweibo://)
騰訊微博: tencentweibo://
淘寶: taobao://
支付寶: alipay://
美團(tuán): imeituan://
知乎: zhihu://
優(yōu)酷: youku://
二、配置Scheme白名單(僅ios掩缓,Android平臺(tái)不需要)
在項(xiàng)目的info.plist中添加一LSApplicationQueriesSchemes雪情,類型為Array。
添加需要支持的項(xiàng)目你辣,類型為字符串類型巡通;
*/