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