I am building a react-native app.The app consists of various courses. These courses are available offline.Using react-native-fs,how can I download 2 or more courses simultaneously?
import { Platform } from "react-native";
import RNFetchBlob from 'rn-fetch-blob'
import { _unzipAll } from "#lib/unZip";
import { DocumentDirectoryPath, LibraryDirectoryPath } from "react-native-fs";
import {
DOWNLOADED_FILE_PATH,
DOWNLOADED_FILE_DIRECTORY
} from "#config/constants";
let parentPath =
Platform.OS === "ios" ? LibraryDirectoryPath : DocumentDirectoryPath;
export function downloadAllFileZip(targetPath, props, id) {
console.log("props id val",id);
console.log("download alll lib", props.courseofflineurl);
try {
RNFetchBlob.config({
path: targetPath
})
.fetch(
"GET",
props.courseofflineurl
)
.progress((received, total) => {
percentage = Math.ceil((received / total) * 100);
console.log("percentage" + percentage)
// getDetails(percentage);
})
.then(res => {
console.log("Downloadedd", res)
_unzipAll(targetPath, parentPath + DOWNLOADED_FILE_DIRECTORY + id, props,id);
})
.catch(error => { });
} catch (error) { }
}
Related
I need bluetooth data of surrounding ibeacons. (device name, mac address, rssi value) I can get these values. But major and minor values are important to me. how can i get them? I use react-native-ble-plx library. What solutions can you suggest me?
Library's Documentation: https://dotintent.github.io/react-native-ble-plx/
My Codes:
import React, { useState } from 'react';
import {
Button,
SafeAreaView,
ScrollView,
StatusBar,
StyleSheet,
Text,
useColorScheme,
View,
} from 'react-native';
import {
Colors,
DebugInstructions,
Header,
LearnMoreLinks,
ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';
import {BleManager} from 'react-native-ble-plx';
import useBLE from './useBLE';
var Buffer = require('buffer/').Buffer;
import base64 from 'react-native-base64';
const Parser = require("binary-parser").Parser;
const App = () => {
const manager = new BleManager();
const {requestPermissions} = useBLE();
useState(() => {
requestPermissions((isGranted) => {
if (!isgranted) {
alert("android permission granted: " + isGranted);
}
});
}, []);
// const ibeacon_format = Struct(
// "uuid" / Array(16, Byte),
// "major" / Int16ub,
// "minor" / Int16ub,
// "power" / Int8sl,
// )
const ibeaconFormat = new Parser()
.int16("major")
.int16("minor");
function deneme() {
manager.startDeviceScan(null, null, (error, device) => {
console.log("device id: ",device.id);
console.log("device name: ", device.localName);
console.log("device rssi: ", device.rssi);
// console.log(device.readCharacteristicForService());
console.log("--------------------");
// let data = new Buffer(device.manufacturerData.toString("base64"));
// console.log(data);
// let data = device.manufacturerData[0x004C];
// let beacon = ibeacon_format.parse(data);
// console.log(beacon);
// let data = Buffer.from(device.manufacturerData, "base64");
// console.log(ibeaconFormat.parse(data));
if (error) {
console.log(error);
}
});
}
function durdur() {
manager.stopDeviceScan();
}
return (
<View>
<Text>Hello World</Text>
<Button title="Deneme" onPress={deneme} />
<Button title="Durdur" onPress={durdur} />
</View>
);
};
export default App;
// let time = date.getTime();
// let seconds = parseInt(time / 1000);
// let data = new Buffer(4);
// data.writeUInt32BE(seconds);
// this.manager.writeCharacteristicWithResponseForDevice(deviceId, serviceUUID, charUUID, data.toString('base64'))
// .then((success) => {
// resolve(success);
// })
// .catch((error) => {
// reject(error)
// })
// });
I was using tipsi-stripe library but now i migrated it to #stripe/stripe-react-native library but i am unable to create token and get country name from card , please let me know how to implement it ,Thanks in advance.
------------------ Tipsi-stripe Code ----------------
import stripe, { PaymentCardTextField, } from 'tipsi-stripe'
stripe
.paymentRequestWithCardForm()
.then(stripeTokenInfo => {
this.state.loading = true
console.log('Token created', { stripeTokenInfo });
-------------- New Code without Create token ---------------------
import { CardField, useStripe ,confirmPayment, loading} from '#stripe/stripe-react-native';
export default class CheckoutSignin extends Component {
state = {
TotalAmount:null,
clientSecret:null
}
componentDidMount(){
console.log("Total Amount : " + this.props.route.params.TotalAmount);
this.state.TotalAmount = this.props.route.params.TotalAmount;
this.setState(this.state)
}
fetchPaymentIntentClientSecret = async () => {
makePayment(100,"AUD").then(r => {
if(r.Status === "Success"){
this.state.clientSecret = r.ClientSecret;
this.setState(this.state)
// alert("Payment Indent Success");
// console.log("1===> "+ clientSecret);
this.handlePayPress();
// console.log("3===> "+ clientSecret);
}
else {
alert("Payment Indent Failed.");
}
}).catch(e => {
alert(e)
})
};
handlePayPress = async () => {
const {paymentIntent, error} = await confirmPayment(this.state.clientSecret, {
paymentMethodType: 'Card',
paymentMethodData: {
// email: _userInfo.email,
},
});
if (error) {
console.log('Payment confirmation error', error);
Alert.alert("Error","Payment confirmation error", error);
} else if (paymentIntent) {
console.log('Success from promise', paymentIntent);
// Alert.alert("Success","Succeed Payment with 3ds");
this.props.navigation.navigate("Thankyou")
}
}
}
I'm using the following code to download a file (can be a PDF or a DOC) and then opening it using Linking.
const { dirs } = RNFetchBlob.fs;
let config = {
fileCache : true,
appendExt : extension,
addAndroidDownloads : {
useDownloadManager : false,
notification : false,
title : 'File',
description : 'A file.',
path: `${dirs.DownloadDir}/file.${extension}`,
},
};
RNFetchBlob.config(config)
.fetch(
method,
remoteUrl,
APIHelpers.getDefaultHeaders()
)
.then((res) => {
let status = res.info().status;
if (status == 200) {
Linking.canOpenURL(res.path())
.then((supported) => {
if (!supported) {
alert('Can\'t handle url: ' + res.path());
} else {
Linking.openURL(res.path())
.catch((err) => alert('An error occurred while opening the file. ' + err));
}
})
.catch((err) => alert('The file cannot be opened. ' + err));
} else {
alert('File was not found.')
}
})
.catch((errorMessage, statusCode) => {
alert('There was some error while downloading the file. ' + errorMessage);
});
However, I'm getting the following error:
An error occurred while opening the file. Error: Unable to open URL:
file:///Users/abhishekpokhriyal/Library/Developer/CoreSimulator/Devices/3E2A9C16-0222-40A6-8C1C-EC174B6EE9E8/data/Containers/Data/Application/A37B9D69-583D-4DC8-94B2-0F4AF8272310/Documents/RNFetchBlob_tmp/RNFetchBlobTmp_o259xexg7axbwq3fh6f4.pdf
I need to implement the solution for both iOS and Android.
I think the easiest way to do so is by using react-native-file-viewer package.
It allows you to Prompt the user to choose an app to open the file with (if there are multiple installed apps that support the mimetype).
import FileViewer from 'react-native-file-viewer';
const path = // absolute-path-to-my-local-file.
FileViewer.open(path, { showOpenWithDialog: true })
.then(() => {
// success
})
.catch(error => {
// error
});
So, I finally did this by replacing Linking by the package react-native-file-viewer.
In my APIHelpers.js:
async getRemoteFile(filePath, extension, method = 'GET') {
const remoteUrl = `${API_BASE_URL}/${encodeURIComponent(filePath)}`;
const { dirs } = RNFetchBlob.fs;
let config = {
fileCache : true,
appendExt : extension,
addAndroidDownloads : {
useDownloadManager : false,
notification : false,
title : 'File',
description : 'A file.',
path: `${dirs.DownloadDir}/file.${extension}`,
},
};
return new Promise(async (next, error) => {
try {
let response = await RNFetchBlob.config(config)
.fetch(
method,
remoteUrl,
this.getDefaultHeaders()
);
next(response);
} catch (err) {
error(err);
}
});
}
In my Actions.js
export function openDocument(docPath, ext) {
return async (dispatch) => {
dispatch(fetchingFile());
APIHelpers.getRemoteFile(docPath, ext).then(async function(response) {
dispatch(successFetchingFile());
let status = response.info().status;
if (status == 200) {
const path = response.path();
setTimeout(() => {
FileViewer.open(path, {
showOpenWithDialog: true,
showAppsSuggestions: true,
})
.catch(error => {
dispatch(errorOpeningFile(error));
});
}, 100);
} else {
dispatch(invalidFile());
}
}).catch(function(err) {
dispatch(errorFetchingFile(err));
});
}
}
In my Screen.js
import { openDocument } from 'path/to/Actions';
render() {
return <Button
title={'View file'}
onPress={() => this.props.dispatchOpenDocument(doc.filepath, doc.extension)}
/>;
}
.
.
.
const mapDispatchToProps = {
dispatchOpenDocument: (docPath, ext) => openDocument(docPath, ext),
}
Are you downloading it from the web? I can see the pdf path is attached at the end of the error path.
For web URLs, the protocol ("http://", "https://") must be set accordingly!
Try to append appropriate schemes to your path. Check it out from the link mentioned below.
This can be done with 'rn-fetch-blob'
RNFetchBlob.android.actionViewIntent(fileLocation, mimeType);
I have installed the plugin implemented the code.. Uploaded the signed apk as Internal tester but when I click the purchase button nothing happens.. Can anyone tell me where am I going wrong
import { Component, OnInit } from '#angular/core';
import { NewTransactionPage } from '../instamojo/new_transaction';
import { IonicPage, Platform, NavController, NavParams } from 'ionic-angular';
import { InAppPurchase2, IAPProduct } from '#ionic-native/in-app-purchase-2/ngx';
#IonicPage()
#Component({
selector: 'page-pay',
templateUrl: 'pay.html',
})
export class PayPage {
public product: any = {
name: 'Upgrade to Pro',
appleProductId: 'android.test.purchased',
googleProductId: 'ultimate'
};
constructor(
public navCtrl: NavController,
public navParams: NavParams,
public platform: Platform,
public store: InAppPurchase2
) {
platform.ready().then(() => {
this.configurePurchasing();
});
}
configurePurchasing() {
if (!this.platform.is('cordova')) { return; }
let productId;
try {
if (this.platform.is('ios')) {
productId = this.product.appleProductId;
} else if (this.platform.is('android')) {
productId = this.product.googleProductId;
}
// Register Product
// Set Debug High
this.store.verbosity = this.store.DEBUG;
// Register the product with the store
this.store.register({
id: productId,
alias: productId,
type: this.store.NON_CONSUMABLE
});
this.registerHandlers(productId);
InAppPurchase2.getPlugin().ready().then((status) => {
console.log(JSON.stringify(this.store.get(productId)));
console.log('Store is Ready: ' + JSON.stringify(status));
console.log('Products: ' + JSON.stringify(this.store.products));
});
// Errors On The Specific Product
this.store.when(productId).error( (error) => {
alert('An Error Occured' + JSON.stringify(error));
});
// Refresh Always
console.log('Refresh Store');
this.store.refresh();
} catch (err) {
console.log('Error On Store Issues' + JSON.stringify(err));
}
}
registerHandlers(productId) {
// Handlers
this.store.when(productId).approved( (product: IAPProduct) => {
// Purchase was approved
product.finish();
});
this.store.when(productId).registered( (product: IAPProduct) => {
console.log('Registered: ' + JSON.stringify(product));
});
this.store.when(productId).updated( (product: IAPProduct) => {
console.log('Loaded' + JSON.stringify(product));
});
this.store.when(productId).cancelled( (product) => {
alert('Purchase was Cancelled');
});
// Overall Store Error
this.store.error( (err) => {
alert('Store Error ' + JSON.stringify(err));
});
}
async purchase() {
/* Only configuring purchase when you want to buy, because when you configure a purchase
It prompts the user to input their apple id info on config which is annoying */
if (!this.platform.is('cordova')) { return };
let productId;
if (this.platform.is('ios')) {
productId = this.product.appleProductId;
} else if (this.platform.is('android')) {
productId = this.product.googleProductId;
}
console.log('Products: ' + JSON.stringify(this.store.products));
console.log('Ordering From Store: ' + productId);
try {
let product = this.store.get(productId);
console.log('Product Info: ' + JSON.stringify(product));
let order = this.store.order(productId);
alert('Finished Purchase');
} catch (err) {
console.log('Error Ordering ' + JSON.stringify(err));
}
}
backHomePage() {
this.navCtrl.pop();
}
}
I have tried building the app without --prod but still its not working. I am calling the purchase() function but nothing happens
I have this code, which can be run after device ready since it's on a secondary route. I'm working on Android at this time.
import { File } from "#ionic-native/file/ngx";
import { FileTransfer, FileTransferObject } from "#ionic-native/file-transfer/ngx";
constructor(private _transfer: FileTransfer,
private _platform: Platform,
private _file: File){
}
startDownload(file: XmatFile): void {
this.docsLoading = !0;
let path = void 0;
let visualPath = "";
if (this._platform.is("ios")) {
path = this._file.documentsDirectory;
visualPath = path;
}
else {
path = this._file.externalRootDirectory + "Download/";
visualPath = path.replace("file://", "");
}
this._checkPaths(path);
const fileTransfer: FileTransferObject = this._transfer.create();
fileTransfer.download(file.url, path + `tmp_${+new Date()}.pdf`, true, {
"content-type": mobSfcContentTypes.pdf
})
.finally(() => this.docsLoading = !1)
.then((downloadedFile) => {
(window as any).resolveLocalFileSystemURL(path, (dir) => {
dir.getFile(file.fileName, {create: true}, (newFile) => {
newFile.createWriter((fileWriter) => {
fileWriter.write(downloadedFile);
fileWriter.onwrite = () => {
this._snack(!0, `File scaricato in ${visualPath}`);
};
}, () => {
this._snack(!1, `Errore salvataggio in ${visualPath}`);
});
});
});
}, (error) => {
console.warn("mob-sfc-help => DOC download error", error);
this._sfcFunctionsSrv.showErrorAlert(`Non è stato possibile scaricare il file ${file.fileName}.
<br />Si prega di riprovare più tardi ed eventualmente aprire un ticket`);
});
}
I have a problem. The download goes ultra quick and saves a two files, but both are very small (a few bytes), while the target pdf is around 2MB.
Am I doing something wrong?
I solved it this way
import {HTTP} from "#ionic-native/http/ngx";
export class MyComponent {
constructor(private _nativeHttp: HTTP) {
}
doDownloadToDevice(file: MyFileModel):void {
this._spinner.show();
this._nativeHttp.downloadFile(file.url, {}, {}, this._downloadPath)
.finally(() => this._spinner.hide())
.then((_r_) => {
console.info("SUCCESS");
}, (e) => {
console.warn("Download error", e);
});
}
Hope this helps.