首先安装

npm install rn-fetch-blob

代码示例

import { View, Text,Button } from 'react-native'
import React from 'react'
import RNFetchBlob from 'rn-fetch-blob';
export default function main03() {
  const downloadAndOpenPDF = async () => {
    const { dirs } = RNFetchBlob.fs;
    const pdfUrl = 'https://example.com/path/to/pdf.pdf';
      let path=`${dirs.DocumentDir}/pdf.pdf`
    const exists = await RNFetchBlob.fs.exists(path);//判断文件里是否有该文件路径
    if(exists){
      //有直接打开
      RNFetchBlob.android.actionViewIntent(path, 'application/pdf');
    }else{
      //没有下载后打开
      try {
        const response = await RNFetchBlob.config({
          fileCache: true,
          appendExt: 'pdf',
          path: `${dirs.DocumentDir}/pdf.pdf`,
        }).fetch('GET', pdfUrl);
        if (Platform.OS === 'ios') {
          await RNFetchBlob.ios.openDocument(response.path());
        } else {
          await RNFetchBlob.android.actionViewIntent(response.path(), 'application/pdf');
        }
      } catch (error) {
        console.log('Error:', error);
      }
    }
   
  };
  return (
    <View>
     <Button title="Download and Open PDF" onPress={downloadAndOpenPDF} />
    </View>
  )
}

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐