React Native Linking 基本用法封裝

Linking提供了一個通用的接口來與傳入和傳出的 App 鏈接進行交互

背景

  • 官方文檔
  • 在App開發中我們經常會用到Linking跳轉,如:跳轉應用市場,撥打手機號,打開微信等等。
  • 下面針對這些需求進行了基本的封裝。

跳轉App應用市場

/**
 * app應用市場下載
 * iOS: itms-apps://itunes.apple.com/cn/app/  +【名稱】/【id + id編號】 如: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('找不到可提供下載的應用市場')
    }
  })
}

撥打手機號

/**
 * 撥打手機
 * @param {*} tel 手機號
 */
export const openTel = (tel) => {
  Linking.canOpenURL(`tel:${tel}`).then(async supported => {
    if (supported) {
      Linking.openURL(`tel:${tel}`)
    } else {
      await Clipboard.setString(tel)
      Toast.show('您的設備不支持,已為您復制手機號!')
    }
  })
}

打開微信

export const openWechat = () => {
 Linking.canOpenURL('weixin://').then(supported => {
   if (supported) {
     Linking.openURL('weixin://')
   } else {
     Alert.alert('沒有安裝微信',
       '請先安裝微信客戶端再打開',
       [
         { 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深度鏈接

  • 結合React Navigation我們可以打開App并跳轉到App任何界面
  • 應用場景:用戶點擊推送消息,打開App并跳轉到消息詳情界面。
  • 假設App中我們有OrderDetailScreen這個界面,router配置如下:
const mainNavigator = createStackNavigator({
....
  order_detail: {
    screen: OrderDetailScreen,
    path: 'order_detail'
  }
....
  • 我們可以使用以下命令跳轉到詳情頁面
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))

常用URL Scheme

/**
  一、常用URL Scheme
    QQ: mqq://
    微信: weixin://
    新浪微博: weibo:// (sinaweibo://)
    騰訊微博: tencentweibo://
    淘寶: taobao://
    支付寶: alipay://
    美團: imeituan://
    知乎: zhihu://
    優酷: youku://
  二、配置Scheme白名單(僅ios,Android平臺不需要)
    在項目的info.plist中添加一LSApplicationQueriesSchemes,類型為Array。
    添加需要支持的項目,類型為字符串類型;
 */
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容