react-native-mail
react-native-mail copied to clipboard
integrate with react-native-image-picker
The react-native-image-picker library doesn't return the filePath URI that react-native-mail expects as the path to the attachment.
For example, right now you expect
// Android
/storage/emulated/0/DCIM/Camera/IMG_20171102_11304344.jpg
// iOS
/Users/anton/Library/Developer/CoreSimulator/Devices/9A15F203-9A58-41C5-A4FC-EA25FAAE92BD/data/Containers/Data/Application/79FF93F9-BA89-4F4C-8809-277BEECD447D/Documents/EFFF0ECE-4063-4FE5-984E-E76506788350.jpg
But what image picker returns is more like this...
file://var/mobile/Containers/Data/Application/983938D-5304-463C-BD05-D033E55F5BEB/Documents/images/224CA6DD-5299-48C3-A7CF-0B645004535F.jpg
So what I've done is...
NSData *fileData = [NSData dataWithContentsOfFile:attachmentPath];
With this code...
// Get the URL string, which is *not* a path (e.g. because it's file:// based)
NSString *attachmentURLString = [RCTConvert NSString:options[@"attachment"][@"path"]];
// Create a URL from the string
NSURL *attachmentURL = [[NSURLComponents componentsWithString:attachmentURLString] URL];
// Get the resource path and read the file using NSData
NSError *error = nil;
NSData *fileData = [NSData dataWithContentsOfURL:attachmentURL options:0 error:&error];
if(fileData == nil) {
// handle error
}
More information surrounding how this solution was arrived at, please see https://stackoverflow.com/questions/47170739/nsdata-assignment-vanishes-becomes-nil-directly-after-assigned#47170815
Working Demo can be found here...
https://github.com/geirman/react-native-photo-emailer