-
Notifications
You must be signed in to change notification settings - Fork 332
/
Copy pathpickImage.ts
62 lines (57 loc) · 1.88 KB
/
pickImage.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import { Platform } from 'react-native';
let ImagePicker;
try {
ImagePicker = require('expo-image-picker');
} catch (e) {
// do nothing
}
if (!ImagePicker) {
console.log(
'expo-image-picker is not installed. Installing this package will enable selecting photos through the native image picker, and thereby send it.',
);
}
export const pickImage = ImagePicker
? async () => {
try {
let permissionGranted = true;
if (Platform.OS === 'ios') {
const permissionCheck = await ImagePicker.getMediaLibraryPermissionsAsync();
const canRequest = permissionCheck.canAskAgain;
permissionGranted = permissionCheck.granted;
if (!permissionGranted) {
if (canRequest) {
const response = await ImagePicker.requestMediaLibraryPermissionsAsync();
permissionGranted = response.granted;
} else {
return { askToOpenSettings: true, cancelled: true };
}
}
}
if (permissionGranted) {
const result = await ImagePicker.launchImageLibraryAsync({
allowsMultipleSelection: true,
mediaTypes: ['images', 'videos'],
preferredAssetRepresentationMode: 'current',
});
const canceled = result.canceled;
if (!canceled) {
const assets = result.assets.map((asset) => ({
...asset,
duration: asset.duration,
name: asset.fileName,
size: asset.fileSize,
type: asset.mimeType,
uri: asset.uri,
}));
return { assets, cancelled: false };
} else {
return { cancelled: true };
}
}
return { cancelled: true };
} catch (error) {
console.log('Error while picking image', error);
return { cancelled: true };
}
}
: null;