Currently I'm dealing with file downloading function of react-native app.
What I'm wondering is how can I show 'Download completed' notification as shown in the image right after the file has downloaded at notification center.
RN Version : 0.61.5
according to https://github.com/cjdell/react-native-fs-test/blob/master/index.common.js
const ret = RNFS.downloadFile({ fromUrl: url, toFile: downloadDest });
ret.promise.then(res => {
// Show Your Notification
}).catch(err => {});
for notification you can use https://github.com/zo0r/react-native-push-notification, this is an example:
RNFS.downloadFile({
fromUrl,
toFile,
}).promise.then((res) => {
PushNotification.localNotification(details)
});
You can use RNFetchBlob package to download any file from the internet and configure the options to show notification, set notification : true, to get the status of download whether complete or ongoing, (only Android), if you keep it false you need to add one more permission in the manifest, i.e DOWNLOAD_WITHOUT_NOTIFICATION
let options = {
fileCache: true,
addAndroidDownloads : {
useDownloadManager : true,
notification : false,
path: PictureDir + "/image_"+Math.floor(date.getTime() + date.getSeconds() / 2)+".png",
description : 'Image'
}
}
config(options).fetch('GET', url)
I used RNFetchBlob to download image/pdf. This helped me to show download notification.
RNFetchBlob.android.addCompleteDownload({
title: "QR Code Image",
description: 'Download complete',
mime: 'image/png',
path: path,
showNotification: true,
})
for me its image file so mime type is "image/png" for pdf its "application/pdf"
Related
I am trying to download a pdf generated through an own api that worked normally for me until yesterday, since then it has stopped working without any modification. Reviewing in developer mode through the metro everything seems to work correctly without any problems (I download the pdf normally), but when deploying the application in the playstore it closes unexpectedly, leaving me without knowing why this happens.
First I was using the React Native Fetch Blob, then I used React Native Blob Util hoping it would solve the problem but it keeps happening. Do you guys have any ideas for why does this happen?
The PDF file download this function:
const generarReciboPdf = async (datosDeuda:FormularioScreenParams,formaPago:ReactText,nroCheque?:string) =>{
const{config,fs} = ReactNativeBlobUtil
if (formaPago === 4 && (nroCheque == ""|| undefined)) {
return console.log('debe llenar todos los campos');
}
const { DownloadDir } = fs.dirs;
const token = await AsyncStorage.getItem('token');
let datosDeudaCompleto= {
...datosDeuda,
forma_pago:formaPago,
nro_cheque:nroCheque
}
let url = 'https://sys.arco.com.py/api/appRecibos/generarReciboPdf/'+JSON.stringify(datosDeudaCompleto)
// return console.log(url);
const options = {
fileCache: true,
addAndroidDownloads: {
useDownloadManager: true, // true will use native manager and be shown on notification bar.
notification: true,
mime:'application/pdf',
path: `${DownloadDir}/recibo_${datosDeuda.mes_deuda.replace(/ /g, "")}_${datosDeuda.razon_social.replace(/ /g, "")}.pdf`,
description: 'Downloading.',
},
};
config(options).fetch('GET', url,{Authorization :'Bearer '+token}).then((res) => {
console.log('se imprimio correctamte el pdf');
setErrorPdf(1)
}).catch((error)=>{
console.log(error);
setErrorPdf(-1);
});
}
Also, this error appears in Play Console: "PlayConsole Error Image".
PlayConsole Error Image
Sharing.shareAsync(url, options)
Opens action sheet to share file to different applications which can handle this type of file.
Arguments
url (string) -- Local file URL to share.
options (object) --
A map of options:
mimeType (string) -- sets mimeType for Intent (Android only)
dialogTitle (string) -- sets share dialog title (Android and Web only)
UTI (string) -- (Uniform Type Identifier) the type of the target file (iOS only)
This is what they say on their page. I dont see any option to share text message along with a local image.
Is there any way to share both the image and text message ?
According to the docs, you should be able to use it like so for Android:
url = '<image-to-be-shared-local-url>';
messageText = 'Text that you want to share goes here';
const options = {
mimeType: 'image/jpeg',
dialogTitle: messageText,
};
Sharing.shareAsync(url, options);
But I would recommend to use react-native-share as this is more widely used and has more options for you to experiment with.
Here is the library documentation
Hope this helps :)
react-native-share still not compatible with expo. you have to use either expo-sharing or Share from react-native.
Example:
ShareMessage = async () => {
if (Platform.OS === "android") {
Share.share({
message: API.base_url + this.state.ShareProductName, // supporting android
url: this.state.share_images[0], // not supporting
title: this.state.ShareProductName,
})
.then((result) => console.log(result))
.catch((errorMsg) => console.log(errorMsg));
return;
} else if (Platform.OS === "ios") {
Share.share({
message:API.base_url + this.state.ShareProductName,
url: this.state.share_images[0],
title: this.state.ShareProductName, // not supporting
})
.then((result) => console.log(result))
.catch((errorMsg) => console.log(errorMsg));
return;
}
};
Description
I am using React-Native-Image-Picker to Select and Upload Files from my App, The issue i am facing that It is working in Android but in ios react-native-image-picker dialog automically closes after launching, therefore i cannot select files for upload.
All the required permissions by ios for file upload have also been given.
How to repeat issue and example
import ImagePicker from 'react-native-image-picker';
import RNFetchBlob from 'react-native-fetch-blob';
var options = {
title: 'Select Image',
quality : 0.25,
storageOptions: {
skipBackup: true,
path: 'images',
},
};
ImagePicker.showImagePicker(options, response => {
console.log('Response = ', response);
RNFetchBlob.fs.stat(response.path)
.then((stats) => {
if (stats.size <= 5000000) {
let source = response;
let checkboxStates = {...this.state.checkboxStates};
checkboxStates['image'] = true;
this.setState({ imagePath: source, imageVisible: true, totalUploadSize: this.state.totalUploadSize + stats.size });
this.setState({checkboxStates});
}
else{
toastMessage('Image should be less than 5 MB');
}
}).catch((err) => {});
});
Additional Information
React Native version: 0.61.5
Platform: IOS
Development Operating System: Mac OS Mojave 10.14.2
Dev tools: Xcode 10.14.2
Device : IPad Pro (IOS 9)
for someone who experience this, in my case this is cause of close of modal of choose option of image upload the open image picker immediately. try to close in given time then open image library or close modal after image picker launched like this :
ImagePicker.launchCamera(imageOptions, async (response) => {
setModalPicker(false)
This happens when the modal that has the option buttons for selecting either from camera or gallery is closed. You can close the modal after selecting an image.
ImagePicker.launchImageLibrary(options, (response) => {
//close the modal here
})
I am attempting to upload video files to YouTube using their v3 API and their MediaUploader. It works in my ReactJS application, but not in my React Native application. When uploading via React Native, the upload completes, then stalls at 100%. In my YouTube account, I can see the new video file, but it is stuck at "Video is still being processed."
I believe the issue may be that I need to send a video file and not an object with a video uri but I don't know how to get around that.
I am using the YouTube MediaUploader from the CORS example at https://github.com/youtube/api-samples/blob/master/javascript/cors_upload.js I am using an OAuth 2.0 client Id, and this setup works correctly when using the ReactJS app via my website. I am using React Native Expo with Camera, which returns me an Object with a URI, for example:
Video File: Object {
"uri": "file:///var/mobile/Containers/Data/Application/353A7969-E2A8-4C80-B641-C80B2B029555/Library/Caches/ExponentExperienceData/%2540dj_walksalot%252Fwandereo/Camera/E971DFEC-AB3E-4B6D-892F-9027AFE47A1A.mov",
}
This file can be viewed in the application, and I can even successfully send this to my server for playback on the web app and in the React Native app. However, sending this object in the MediaUploader does not work. It will take an appropriate amount of time to upload, but then sits at 100%, while my YouTube account will show it has received the video with the correct metadata, but the video itself remains stuck at "Video is still being processed."
video_file: Object {
"uri": "file:///var/mobile/Containers/Data/Application/353A7969-E2A8-4C80-B641-C80B2B029555/Library/Caches/ExponentExperienceData/%2540dj_walksalot%252Fwandereo/Camera/E971DFEC-AB3E-4B6D-892F-9027AFE47A1A.mov",
}
export const uploadToYouTube = (access_token, video_file, metadata) => async (dispatch) => {
...cors_upload...
var uploader = new MediaUploader({
baseUrl: `https://www.googleapis.com/upload/youtube/v3/videos?part=snippet%2Cstatus&key=API_KEY`,
file: video_file,
token: access_token,
metadata: metadata,
contentType: 'video/quicktime',
// contentType: 'application/octet-stream',//"video/*",
// contentType = options.contentType || this.file.type || 'application/octet-stream';
params: {
part: Object.keys(metadata).join(',')
},
onError: function(data) {
// onError code
let err = JSON.parse(data);
dispatch(returnErrors(err.message, err.code))
console.log('Error: ', err);
},
onProgress: function(progressEvent){
// onProgress code
let percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
dispatch({
type: UPLOAD_PROGRESS,
payload: percentCompleted
});
},
onComplete: function(data) {
console.log('Complete');
// onComplete code
let responseData = JSON.parse(data);
dispatch({
type: UPLOAD_YOUTUBE_VIDEO,
payload: JSON.parse(data)
})
dispatch({
type: UPLOAD_PROGRESS,
payload: 0
});
}
});
uploader.upload();
}
Similar to my currently-working web app, after completing the upload, the "onComplete" function should fire, and YouTube should process the video. This does not happen. I believe it's because I'm attaching an object with a URI and not the actual file.
I was able to solve this from a post at Expert Mill by Joe Edgar at https://www.expertmill.com/2018/10/19/using-and-uploading-dynamically-created-local-files-in-react-native-and-expo/
By using fetch and .blob() I was able to convert the URI object to a data object and upload. Additional code:
const file = await fetch(video_file.uri);
const file_blob = await file.blob();
No need to install RNFetchBlob since this is in the Expo SDK.
How to open a web browser in expo rather than using the expo browser.I want open the browser in inside the app.
you can use the following library react-native-inappbrowser
follow the installation from the github page
import { Linking } from 'react-native'
import InAppBrowser from 'react-native-inappbrowser-reborn'
...
async openLink() {
try {
const url = 'https://www.google.com'
if (await InAppBrowser.isAvailable()) {
const result = await InAppBrowser.open(url, {
// iOS Properties
dismissButtonStyle: 'cancel',
preferredBarTintColor: '#453AA4',
preferredControlTintColor: 'white',
readerMode: false,
animated: true,
modalPresentationStyle: 'overFullScreen',
modalTransitionStyle: 'partialCurl',
modalEnabled: true,
// Android Properties
showTitle: true,
toolbarColor: '#6200EE',
secondaryToolbarColor: 'black',
enableUrlBarHiding: true,
enableDefaultShare: true,
forceCloseOnRedirection: false,
// Specify full animation resource identifier(package:anim/name)
// or only resource name(in case of animation bundled with app).
animations: {
startEnter: 'slide_in_right',
startExit: 'slide_out_left',
endEnter: 'slide_in_left',
endExit: 'slide_out_right'
},
headers: {
'my-custom-header': 'my custom header value'
},
waitForRedirectDelay: 0
})
Alert.alert(JSON.stringify(result))
}
else Linking.openURL(url)
} catch (error) {
Alert.alert(error.message)
}
}
...
you can check the example app here
for expo it becomes little bit complicated please check the related tutorial by Medium
if you want reading mode in ios please refer this link
reader-mode-webview-component-for-react-native
The expo-web-browser package opens an in app browser.
This worked for me with expo. I tried react-native-inappbrowser-reborn first, but isAvailable() was throwing an error.
import * as WebBrowser from 'expo-web-browser'
...
WebBrowser.openBrowserAsync(url, {showTitle: true})