-
Notifications
You must be signed in to change notification settings - Fork 374
Expand file tree
/
Copy pathpickImage.ts
More file actions
68 lines (63 loc) · 2.19 KB
/
pickImage.ts
File metadata and controls
68 lines (63 loc) · 2.19 KB
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
63
64
65
66
67
68
import { Platform } from 'react-native';
import mime from 'mime';
import { PickImageOptions } from 'stream-chat-react-native-core';
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 ({ maxNumberOfFiles }: PickImageOptions = {}) => {
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',
selectionLimit: maxNumberOfFiles,
});
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 ||
mime.getType(asset.fileName || asset.uri) ||
(asset.duration ? 'video/*' : 'image/*'),
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;