Skip to content

Instantly share code, notes, and snippets.

@kukiron
Forked from Aliath/AttachmentPicker.ts
Created March 5, 2020 14:56
Show Gist options
  • Save kukiron/444af20e088f28511a03cd26fc1c0765 to your computer and use it in GitHub Desktop.
Save kukiron/444af20e088f28511a03cd26fc1c0765 to your computer and use it in GitHub Desktop.
Wrapper for the react-native-image-picker and react-native-document-picker. Allow to pick media from gallery on iOS.
import { Platform, ActionSheetIOS } from 'react-native';
import DocumentPicker from 'react-native-document-picker';
import ImagePicker from 'react-native-image-picker';
import RNFS from 'react-native-fs';
type Captions = {
image: string,
document: string,
cancel: string,
title: string,
};
export class AttachmentPicker {
private _captions: Captions;
constructor(captions: Captions = { image: 'Image', document: 'Document', cancel: 'Cancel', title: 'Pick type of media' }) {
this._captions = captions;
}
pick = () => {
if (Platform.OS === 'ios') {
return this._pickIOS();
}
return new Promise((resolve, reject) => {
return this._pickDocument(resolve, reject);
});
}
_pickIOS = () => {
return new Promise((resolve, reject) => {
const { image, document, cancel, title } = this._captions;
const options = [image, document, cancel];
const handlers = [this._pickImage, this._pickDocument, this._pickClosed];
const cancelButtonIndex = options.indexOf(cancel);
ActionSheetIOS.showActionSheetWithOptions(
{ options, cancelButtonIndex, title },
buttonIndex => { handlers[buttonIndex](resolve, reject); }
);
});
}
_pickImage = (resolve: (payload: any) => void, reject: (payload: any) => void) => {
ImagePicker.showImagePicker(response => {
if (response.didCancel) {
reject(new Error('Action cancelled!'));
} else {
const { data: b64Content, type: fileType } = response;
const b64 = `data:${fileType};base64,${b64Content}`;
const fileExtension = String(fileType).substr(String(fileType).indexOf('/') + 1);
resolve({ b64, fileType, fileExtension });
}
});
}
_pickDocument = async (resolve: (payload: any) => void, reject: (payload: any) => void) => {
try {
const result = await DocumentPicker.pick({
type: [DocumentPicker.types.images, DocumentPicker.types.pdf]
});
const fileType = result.type;
const fileExtension = fileType.substr(fileType.indexOf('/') + 1);
const realURI = Platform.select({ android: result.uri, ios: decodeURI(result.uri), })
const b64Content = await RNFS.readFile(realURI, "base64")
const b64 = `data:${fileType};base64,${b64Content}`;
resolve({ b64, fileType, fileExtension });
} catch {
reject(new Error('Action cancelled!'));
}
}
_pickClosed = (_: any, reject: (payload: any) => void) => {
reject(new Error('Action cancelled!'));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment