1import * as DocumentPicker from 'expo-document-picker';
2import React from 'react';
3import { Alert, Image, 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 [document, setDocument] = React.useState<DocumentPicker.DocumentResult | null>(null);
11
12  const openPicker = async () => {
13    const result = await DocumentPicker.getDocumentAsync({
14      copyToCacheDirectory: copyToCache,
15    });
16    if (result.type === 'success') {
17      setDocument(result);
18    } else {
19      setTimeout(() => {
20        Alert.alert('Document picked', JSON.stringify(result, null, 2));
21      }, 100);
22    }
23  };
24
25  return (
26    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
27      <Button onPress={openPicker} title="Open document picker" />
28      <TitleSwitch
29        style={{ marginVertical: 24 }}
30        value={copyToCache}
31        setValue={setCopyToCache}
32        title="Copy to cache"
33      />
34      {document?.type === 'success' && (
35        <View>
36          {document.name!.match(/\.(png|jpg)$/gi) ? (
37            <Image
38              source={{ uri: document.uri }}
39              resizeMode="cover"
40              style={{ width: 100, height: 100 }}
41            />
42          ) : null}
43          <Text>
44            {document.name} ({document.size! / 1000} KB)
45          </Text>
46          <Text>URI: {document.uri}</Text>
47        </View>
48      )}
49    </View>
50  );
51}
52
53DocumentPickerScreen.navigationOptions = {
54  title: 'DocumentPicker',
55};
56