How to get file from URI | Expo | React Native - ios

I have ejected project of the expo.
After changing info.plist, now I am able to get my app in the list of "open with app list" and actually able to open that file with my expo(React native app).
App.js
Linking.getInitialURL().then((url) => {
if (url) {
console.log(url);
}
}).catch(err => console.error('An error occurred', err));
this code is giving me this URL.
file:///private/var/mobile/Containers/Data/Application/7E55EB55-7C49-4C0C-B4CB-63AC4F49689E/Documents/Inbox/matters-3.csv
So, that means now I have URL of the email attachment, but How am I able to get the data of that csv string in my app?
So I am assuming, when I click open with my app. The URL that is passed into my app from the system is actually a copy of the document that is placed somewhere in our app’s directory.
But when I trying to access this file with Expo.FileSystem. readAsStringAsync it's giving me an error says, the file is not readable.
is there anything to do with storage permission?
Need Help....?

I think you could use react-native-fs. This here should work and print out the contents of the CSV file to the console.
App.js
var RNFS = require('react-native-fs');
Linking.getInitialURL().then((url) => {
if (url) {
RNFS.readFile(url).then((data) => {
console.log(data);
}
}).catch(err => console.error('An error occurred', err));

You can use react-native-fs as Carlo mentioned or rn-fetch-blob, I recommend rn-fetch-blob, to read a file u can check their documentation, it goes something like this
let data = '';
RNFetchBlob.fs.readStream( ...options).then((ifstream) => {
ifstream.open()
ifstream.onData((chunk) => {
data += chunk
// show progress ...%
})
ifstream.onError((err) => {
console.log('oops', err)
})
ifstream.onEnd(() => {
consol.log('final data', data)
})
}))

Related

Is there a way to load local files into HTML in Electron? Getting ERR_UNKNOWN_URL_SCHEME

I have an Electron app that's trying to load a local audio file into an HTML5 <audio> element. The path itself is fine file:///../song.mp3 and I've set webSecurity to false, but I'm still getting Failed to load resource: net::ERR_UNKNOWN_URL_SCHEME. From that same error, if I copy the address and paste it into my browser, I get the correct file.
Are there any other settings I need to change to get this to work?
Appreciate your time
I think this is a bug. The URL scheme of the file is not enabling as a URL scheme.
You can use this code below inside of app.on('ready'....:
protocol.registerFileProtocol('file', (request, cb) => {
const url = request.url.replace('file:///', '')
const decodedUrl = decodeURI(url)
try {
return cb(decodedUrl)
} catch (error) {
console.error('ERROR: registerLocalResourceProtocol: Could not get file path:', error)
}
})
it will be fixed

Sent a file from backend to frontend. Cannot restore its old form

here I have a function that reacts to a button click
and gains a file from my backend.
onDownload() {
this.http.get('http://localhost:8080/backend/invoice/1/download',
{responseType: 'blob'})
.subscribe(res =>
console.log(res))
}
So far, I am happy because inside the chrome console I dont get any errors.
The response looks like this in the console:
The return type of the Java backend was InputStream (method annotation #Produces(MediaType.MULTIPART_FORM_DATA))
Then I found
https://stackblitz.com/edit/angular-blob-file-download?file=app%2Fapp.component.ts
and looked at ngOnInit() in app.component.ts
ngOnInit() {
const data = 'some text';
const blob = new Blob([data], { type: 'application/octet-stream' });
this.fileUrl = this.sanitizer.bypassSecurityTrustResourceUrl(window.URL.createObjectURL(blob));
}
Currently, I think my frontend receives a blob.
So, I can start in the line starting with "this.fileUrl="
and input my blob.
Inside the .html, I have a button to start the onDownload() function
and another tag to save the file on my local hard drive.
<div>
<button (click)="onDownload()">Herunterladen</button>
</div>
<a [href]="safeResourceUrl" download="file.txt">DownloadFile</a>
Meanwhile, I change the onDownload() method to
onDownload() {
this.http.get('http://localhost:8080/backend/invoice/1/download',
{responseType: 'blob'})
.subscribe(res => this.safeResourceUrl=this.sanitizer.bypassSecurityTrustResourceUrl(window.URL.createObjectURL(res)))
}
After I click "Herunterladen" and then the DownloadFile link I get either
a .txt file that I cannot read
or, if I change the file name to .pdf in the a tag inside the .html,
I get a "failed to load pdf document"
All I want is to get my original pdf that I stored in my database and that was sent from the backend.
Has anyone had the same problem before? Thank you for your help.
I changed my function to
onDownload() {
window.open(`http://localhost:8080/backend/invoice/${this.invoice.invoiceNr}/download`, 'blank');
}
Now it works:)

React native PouchDB get hangs

I have a promise chain where I get the content from local DB, update it with the latest fetched from API. This cycle is run whenever user eg opens a content. It works well. Except when the user is opening the app through a deep link. Eg, I go to the company website, I have the deep link option in the safari, I open it. It successfully fetches the content opened from the website, goes into the promise lifecycle where it tries to load and update the content but it just hangs. All input data is correct and it doesn't make sense why it hangs at all.
PouchDB is using adapter pouchdb-adapter-react-native-sqlite with react-native-sqlite-2
createDBIndex()
.then(() => {
console.groupCollapsed('Updating existing content');
console.log(toUpdateArray);
console.log('Fetching articles and indexes');
return Promise.all(toUpdateArray.map(({ _id }) => DB.articles.get(_id)));
})
.then(dbArticles => {
console.log('Resolving finders-keepers');
console.log(dbArticles);
const updatedContent = dbArticles.map(dbItem => {
const toUpdate = toUpdateArray.find(item => item._id === dbItem._id);
return {
...dbItem,
...toUpdate,
expire: moment().add(1, 'd').format()
};
});
return DB.articles.bulkDocs(updatedContent).then(() => updatedContent);
})
.then(updatedDBArray => {
console.log('update result', updatedDBArray);
console.groupEnd();
return updatedDBArray;
})
The last console.log it gives is Fetching articles and indexes and the whole app freeze. tried to print the PouchDB get function result or error but nothing. It doesn't get resolved or rejected.
What I can share is that recently people have problems using PouchDB in a React Native environment which is using AsynchStorage as its backing storage. Take a look at this question and that question and also this issue.

in-app purchase Object {message: "Billing is not initialized", code: -3, errorCode: -3}

I am working on ionic meteor using the in-app purchase plugin "cordova-plugin-inapppurchase" (https://github.com/AlexDisler/cordova-plugin-inapppurchase).
When I request 'inAppPurchase.buy(productId)' , I get an error "Object {message: "Billing is not initialized", code: -3, errorCode: -3}"
My code is :
inAppPurchase
.buy('com.myapp.prod1')
.then(function (data) {
console.log(data);
})
.catch(function (err) {
console.log(err);
});
Ionic Information
For ios, it is pretty straight forward, but for android, you need to go to Google playstore, development tool, services and api then copy the base 64 licensing key.
Create a file called manifest.json in the src directory of your ionic project then add the key inside the file in the format below.
{ "play_store_key": "<Base64-encoded public key from the Google Play Store>" }
Add the file to the www folder of the ionic project by adding the path to the angular.json file found in the root folder of the project as shown below.
Sample of angular.json file
call getproducts method before buy or subscribe to initialize the store.
inAppPurchase
.getProducts([
'product.id'
])
.then(function (products) {
$log.debug(products);
})
.catch(function (err) {
$log.error(err);
});
Follow the rest of the instructions here (https://github.com/AlexDisler/cordova-plugin-inapppurchase) and It should work perfectly. Thank you.
got the same error but, I can see that it helps to do:
inAppPurchase
.getProducts([
'product.id'
])
.then(function (products) {
$log.debug(products);
})
.catch(function (err) {
$log.error(err);
});
even through you are fetching your products from, say dbs.
The error (Billing is not initialized) message disappeared after I called the "restore purchases" first.
I now can see the Google Play "BUY" popup screen.

Download ZIP file in react-native

I'm writing an app using react-native and I will build it for both android and iOS.
Anyway, I have been trying to download a ZIP-file using react-native but I can't get it to work. After I have downloaded the file my plan is to unzip it and then store it using AsyncStorage.
But I keep getting the error below:
[RCTNetworking.m:330] Received data was not a string, or was not a recognised encoding.
I have tried various settings for my request but I guess I am simply missing something, the code currently looks like:
fetch('somewhere.path/file.zip', {
method: 'GET',
headers: {
'Accept-Encoding': 'application/zip'
},
})
.then((response) => {
console.log("Success");
})
.catch((error) => {
console.log("Error");
}).done();
Success gets printed but the response data does not contain the zip files data.
If it helps I am debugging using XCode and the simulator.
If anybody has any ideas please help me out! :)
Thanks in advance,
Yon
I also write an app to download some zip files and unzip it. And for download function, I using a plugin called react-native-fetch-blob. Code example:
import RNFetchBlob from 'react-native-fetch-blob';
...
RNFetchBlob.config({
fileCache : true,
path: path + '/file.zip'})
.fetch('GET','http://domain/file.zip')
.progress((received, total) => {console.log('progress', received / total)})
.then((res) => {// the temp file path
console.log('The file saved to ', res.path());
});
...
Thanks,

Resources