如何在React Native中获取Android内部存储中所有可用的pdf文件

问题描述 投票:0回答:1

我正在使用react-native-fs来读取设备外部存储中的文件。我想获取存储在 Android 设备中的所有 pdf 书籍并在屏幕中列出它们。在谷歌中搜索,阅读react-native-fs中的文档,但没有成功获取所有pdf书籍。如果我的代码有问题,请帮忙。

我做错了什么?

这是我的代码。

import React, { useState, useEffect } from 'react';
import {
  Alert,
  StyleSheet,
  Text,
  View,
  Dimensions,
  ImageBackground,
  ScrollView,
  PermissionsAndroid,
  ActivityIndicator,
} from 'react-native';

import RNFS from 'react-native-fs';
import BookOffline from '../components/BookOffline';

const MyBooks = ({ navigation }) => {
  // collecting data from device
  const [books, setBooks] = useState([])
  const [bookList, setBookList] = useState([]);

  useEffect(() => {
    getPermission();
  }, []);


  const getPermission = async () => {
    try {
      PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE
      ).then(granted => {
        if (granted === PermissionsAndroid.RESULTS.GRANTED) {
          readStorage();
        } else {
          //If permission denied then show alert
          Alert.alert('Not Granted storage_permission');
          navigation.goBack();
        }
      });
    } catch (err) {
      //To handle permission related issue
      console.log('error', err);
    }
  };


  const readStorage = async () => {
    let list2 = [];
    await RNFS.readDir(RNFS.ExternalStorageDirectoryPath) // On Android, use "RNFS.DocumentDirectoryPath" (MainBundlePath is not defined)
      .then(result => {
        result.forEach((item, index) => {
          // console.log(index, item)
          if (item.name.endsWith('.pdf')) {
            setBooks([...books, item])
          }
          else if (item.isDirectory()) {
            RNFS.readDir(item.path)
              .then(result => {
                list2 = result.filter((item) => item.name.endsWith('.pdf'))
                setBooks([...books, ...list2])
              }).catch((error) => {
                console.log(error)
              })
          }
        });
        setBookList(books)
        console.log("bookList", bookList)
      })
      .catch(error => {
        console.log(error);
      });
  };


  return bookList.length == 0 ? (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Text>Loading...</Text>
      <ActivityIndicator size="large" />
    </View>
  ) : (
    <View style={{ justifyContent: 'center', alignItems: 'center' }}>
      <ImageBackground
        source={require('../assets/images/tech-dark-design.jpg')}
        resizeMode="cover"
        style={{ width: '100%' }}>
        <ScrollView style={styles.images}>
          {bookList.map((item, index) => {
            return <BookOffline data={item} key={index} />;
          })}
        </ScrollView>
      </ImageBackground>
    </View>
  );
};

export default MyBooks;

const styles = StyleSheet.create({
  container: {
    height: Dimensions.get('window').height - 110,
    //  padding: 5,
  },
  list: {
    width: '100%',
    shadowColor: '#000',
    shadowOffset: {
      width: 0,
      height: 1,
    },
    shadowOpacity: 0.2,
    shadowRadius: 1.41,
    elevation: 2,
    marginBottom: 1,
  },
});
react-native pdf react-native-fs
1个回答
0
投票

我也面临着同样的问题。你能修复它吗?

© www.soinside.com 2019 - 2024. All rights reserved.