【问题标题】:How to download a pdf file in a react-native iOS webview?如何在本机 iOS webview 中下载 pdf 文件?
【发布时间】:2023-01-01 11:59:20
【问题描述】:

只需使用 expo 和 react-native-webview 库开发一个简单的 react-native 应用程序。 问题是当用户尝试下载 pdf 格式的发票时,iOS 会显示预览并且无法返回到应用程序。

这里附上主要的应用程序屏幕组件:

import React, { useState } from "react";
import { ActivityIndicator, Share, StyleSheet } from "react-native";
import * as FileSystem from 'expo-file-system';
const { downloadAsync, documentDirectory } = FileSystem;

import { SafeAreaView } from 'react-native-safe-area-context';
import { WebView } from 'react-native-webview';

const HomeScreen = ({ navigation }) => {
  const [loading, setLoading] = useState(true);

  let downloadDocument = async (downloadUrl) => {
    alert('downloadUrl 2: ', downloadUrl);
    let fileURI = await downloadAsync(
        downloadUrl,
        `${documentDirectory}/invoice.pdf`,
        {}
    );
    await onShare(fileURI.uri);
  }

  const onShare = async (url) => {
    try {
        return Share.share({
            message: 'Select storage location',
            url: url
        });
    } catch (error) {
        alert('error: ', error);
        return error;
    }
  };

  return (
    <SafeAreaView style={styles.container}>
      <WebView
        source={{ uri: '<url>' }}
        onError={() =>
          navigation.navigate('Error')
        }
        setSupportMultipleWindows={false}
        startInLoadingState={true}
        renderLoading={() => 
          <ActivityIndicator
            style={styles.spinner}
            size='large'
            color='#0098D4'
          />
        }
        domStorageEnabled={true}
        // iOS
        onFileDownload={({ nativeEvent: { downloadUrl } }) => {
          alert('downloadUrl: ', downloadUrl);
          downloadDocument(downloadUrl);
        }}
      />
    </SafeAreaView>
  );
}

我们添加了一些警报,但从未触发过。

在 html 代码中,有一个带有 href 属性的标记指向文件的 url 和下载选项集。

任何解决方案?

【问题讨论】:

    标签: react-native expo react-native-webview


    【解决方案1】:

    你可以使用模态,或者把按钮放在 webview 的顶部

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-16
      • 1970-01-01
      相关资源
      最近更新 更多