1import * as DocumentPicker from 'expo-document-picker';
2import React from 'react';
3import { Alert, FlatList, Image, Platform, Text, View } from 'react-native';
4
5import Button from '../components/Button';
6import TitleSwitch from '../components/TitledSwitch';
7
8export default function DocumentPickerScreen() {
9  const [copyToCache, setCopyToCache] = React.useState(false);
10  const [multiple, setMultiple] = React.useState(false);
11  const [pickerResult, setPickerResult] =
12    React.useState<DocumentPicker.DocumentPickerResult | null>(null);
13
14  const openPicker = async () => {
15    const time = Date.now();
16    const result = await DocumentPicker.getDocumentAsync({
17      copyToCacheDirectory: copyToCache,
18      multiple,
19    });
20    console.log(`Duration: ${Date.now() - time}ms`);
21    console.log(`Results:`, result);
22    if (!result.canceled) {
23      setPickerResult(result);
24    } else {
25      setTimeout(() => {
26        if (Platform.OS === 'web') {
27          alert('Cancelled');
28        } else {
29          Alert.alert('Cancelled');
30        }
31      }, 100);
32    }
33  };
34
35  return (
36    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
37      <Button onPress={openPicker} title="Open document picker" />
38      <TitleSwitch
39        style={{ marginVertical: 10 }}
40        value={copyToCache}
41        setValue={setCopyToCache}
42        title="Copy to cache"
43      />
44      <TitleSwitch
45        style={{ marginVertical: 10 }}
46        value={multiple}
47        setValue={setMultiple}
48        title="Pick multiple"
49      />
50      <FlatList
51        data={pickerResult?.assets}
52        keyExtractor={(item) => item.uri}
53        renderItem={({ item: document }) => {
54          return (
55            <View>
56              {document.name!.match(/\.(png|jpg)$/gi) ? (
57                <Image
58                  source={{ uri: document.uri }}
59                  resizeMode="cover"
60                  style={{ width: 100, height: 100 }}
61                />
62              ) : null}
63              <Text>
64                {document.name} ({document.size! / 1000} KB)
65              </Text>
66              <Text>
67                URI: {document.uri} MimeType: {document.mimeType}
68              </Text>
69            </View>
70          );
71        }}
72      />
73    </View>
74  );
75}
76
77DocumentPickerScreen.navigationOptions = {
78  title: 'DocumentPicker',
79};
80