I am using react-native-fetch-blob for download image.
Here's my source code.
downloadThumb(element) {
return new Promise((resolve, reject) => {
RNFetchBlob.config({
// add this option that makes response data to be stored as a file,
// this is much more performant.
fileCache: true,
path: `${DocumentDirectoryPath}/thumbs/${element}`,
})
.fetch(
'GET',
`https://www.searchforsites.co.uk/images/thumbs/${element}`,
{
// some headers ..
},
)
.then((res) => {
resolve(true);
})
.catch((err) => {
// console.log('Error: ', err);
// this.setState({ modalOpen: false, regionUpdated: true });
// this.findUser();
reject(true);
});
});
}
///////////////////////////////////////
recursive_thumb(element) {
this.downloadThumb(element).then((response) => {
if (this.state.count > this.state.total_thumbs) {
this.setState({ modalOpen: false });
setThumbDownloaded();
return true;
}
this.state.count += 1;
// console.log(this.state.count);
this.setState({ totalCount: this.state.total_thumbs, fetchedCount: this.state.count });
this.recursive_thumb(this.state.thumbs[this.state.count]);
});
}
filesize is around 8KB. Now I am donwloading one by one.
And downloading one image(8KB) takes a second.
Is there any solution to improve downloading speed?
Thanks for your time.
If you'd like to increase the download of a sequence of images:
Just create a Promise.all, which will fetch them all parallel
Promise.all([
downloadThumb('data.jpeg'),
downloadThumb('users.jpeg'),
downloadThumb('products.jpeg')
])
.then(function(data) {
console.log('Parallel promises >>>', data);
});
Check out this github page: https://github.com/jaydson/es7-async
Related
Hello I have a streaming service, (it is an online radio) that I need to stream in my app, the url it is the following
https://cast.uncuartocomunicacion.com:8020/live
I have been using react native sound player to stream it but I had issues with android's performance. So I switched to react native track player, but I haven't been able of playing the streaming service.
the following it is the code I have been using.
const start = async () => {
await TrackPlayer.setupPlayer();
await TrackPlayer.add({
id: 'trackI1',
url: 'https://cast.uncuartocomunicacion.com:8020/live',
title: 'Area deportiva',
artist: 'Area deportiva',
artwork: {
uri:
'https://pbs.twimg.com/profile_images/1480935488232075270/STi9FaUo_400x400.jpg',
},
});
TrackPlayer.updateOptions({
stopWithApp: false,
});
setLoading(false);
};
useEffect(() => {
//let isMounted = true;
//Alert.alert(audioUrl);
//getUrl();
//SoundPlayer.loadUrl('https://cast.uncuartocomunicacion.com:8020/live');
/*TrackPlayer.setupPlayer()
.then(() => {
setLoading(false);
})
.catch((e) => {
setLoading(false);
});*/
start()
.then()
.catch((e) => {
Alert.alert('e ' + JSON.stringify(e));
});
}, []);
const handlePlayPause = () => {
console.warn('asa is playing ', isPlaying);
/* */
try {
/* !isPlaying ? SoundPlayer.resume() : SoundPlayer.pause();*/
if (!isPlaying) {
Alert.alert('enre aquiu ');
TrackPlayer.play()
.then((r) => {
Alert.alert('then play' + JSON.stringify(r));
})
.catch((e) => {
Alert.alert('e ' + JSON.stringify(e));
});
} else {
TrackPlayer.pause().then((r) => console.log(r));
}
} catch (e) {}
setIsPlaying(!isPlaying);
};
I hope someone can help me!!!
For some reason when you play audio with SSL and use another port (8020) it doesn't work, but you can try using http and add
android:usesCleartextTraffic="true"
in AndroidManifest
I have made a function that checks for internet availability. whenever I call this function it gives me true every time whether the internet is ON or OFF. I want to have one function that contains code to check the internet and I can call it before fetching data from the internet . my code is below.
const [campusList, setCampusList]= React.useState([{label:'Select Campus', value:'select campus'}]);
const isConnected =()=>{
NetInfo.fetch().then(state => {
console.log("Connection type", state.type);
console.log("Is connected?", state.isConnected);
if(state.isConnected)
return true;
else
return false;
});
}
const loadCampuses = async()=>{
if(isConnected)
{
await fetch(url)
.then((respons)=>respons.json())
.then((jsonResponse)=>{
jsonResponse.map((data)=>
setCampusList(campusList=> [...campusList, {label:data.Text, value:data.Value}])
);
})
.catch((error)=>console.log(error))
//.finally(()=>setLoading(false))
}
}
fetch Returns a Promise that resolves to a NetInfoState object. you need to wait promise to resolve
try this
const isConnected = sendRequest => {
NetInfo.fetch().then(state => {
if (state.isConnected) {
sendRequest();
}
});
};
const loadCampuses = () => {
isConnected(async () => {
await fetch(url)
.then(respons => respons.json())
.then(jsonResponse => {
jsonResponse.map(data =>
setCampusList(campusList => [
...campusList,
{ label: data.Text, value: data.Value },
]),
);
})
.catch(error => console.log(error));
});
};
oh right, it's a promise, not just a straight return. you need to await for it. You don't need a separate function:
if(await NetInfo.fetch().isConnected)
geolocation.getCurrentPosition() is not working in Android mobiles, is this an Ionic bug? Or is there any better solution to achieve this?
ngOnInit() {
this.geolocation.getCurrentPosition().then((resp) => {
}).catch((error) => {
console.log('Error getting location', error);
});
let watch = this.geolocation.watchPosition();
watch.subscribe((data) => {
this.data = data;
this.currentLat = data.coords.latitude;
this.currentLng = data.coords.longitude;
this.accuracy = data.coords.accuracy;
});
}
I had this issue once and was able to solve it by enabling High Accuracy GPS on the mobile device.
You can use the Location Accuracy Plugin
https://ionicframework.com/docs/native/location-accuracy
to activate high accuracy mode when loading the application
import { LocationAccuracy } from '#ionic-native/location-accuracy/ngx';
constructor(private locationAccuracy: LocationAccuracy) { }
...
this.locationAccuracy.canRequest().then((canRequest: boolean) => {
if(canRequest) {
this.locationAccuracy.request(this.locationAccuracy.REQUEST_PRIORITY_HIGH_ACCURACY).then(
() => console.log('Request successful'),
error => console.log('Error requesting location permissions', error)
);
}
});
or you can simply pass
this.geolocation.getCurrentPosition({ enableHighAccuracy : true, timeout: 10000 } )
Try setting the next values in the variable options
import { Geolocation, Geoposition } from '../../node_modules/#ionic-native/geolocation';
constructor(private geolocation: Geolocation)
...
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
this.geolocation.getCurrentPosition(options)
.then((result: Geoposition) => {
console.log(result)
})
.catch(error => {
console.error(error)
})
});
How do we implement caching in react-native-video? Basically, when a video is currently streaming from a network resource, how do we save the video somewhere, and then retrieve it when the same resource is access. What is the best approach for this?
The best approach that i would refer you is using react-native-fetch-blob, you can implement it like this:
const RNFetchBlob = require('react-native-fetch-blob').default;
const {
fs
} = RNFetchBlob;
const baseCacheDir = fs.dirs.CacheDir + '/videocache';
//call the downloadVideo function
downloadVideo('http://....',baseCacheDir)
//Function to download a file..
const activeDownloads = {};
function downloadVideo(fromUrl, toFile) {
// use toFile as the key
activeDownloads[toFile] = new Promise((resolve, reject) => {
RNFetchBlob
.config({path: toFile})
.fetch('GET', fromUrl)
.then(res => {
if (Math.floor(res.respInfo.status / 100) !== 2) {
throw new Error('Failed to successfully download video');
}
resolve(toFile);
})
.catch(err => {
return deleteFile(toFile)
.then(() => reject(err));
})
.finally(() => {
// cleanup
delete activeDownloads[toFile];
});
});
return activeDownloads[toFile];
}
//To delete a file..
function deleteFile(filePath) {
return fs.stat(filePath)
.then(res => res && res.type === 'file')
.then(exists => exists && fs.unlink(filePath)) //if file exist
.catch((err) => {
// swallow error to always resolve
});
}
Cheers:)
Does anyone have an example on how to use promise with GraphRequestManager?
I get Cannot read property then of undefined error in my action creator.
function graphRequest(path, params, token=undefined, version=undefined, method='GET') {
return new Promise((resolve, reject) => {
new GraphRequestManager().addRequest(new GraphRequest(
path,
{
httpMethod: method,
version: version,
accessToken: token
},
(error, result) => {
if (error) {
console.log('Error fetching data: ' + error);
reject('error making request. ' + error);
} else {
console.log('Success fetching data: ');
console.log(result);
resolve(result);
}
},
)).start();
});
}
I call the above using my action creator
export function accounts() {
return dispatch => {
console.log("fetching accounts!!!!!!");
dispatch(accountsFetch());
fbAPI.accounts().then((accounts) => {
dispatch(accountsFetchSuccess(accounts));
}).catch((error) => {
dispatch(accountsFetchFailure(error));
})
}
}
I get 'Success fetching data:' in the console along with the result before the error. So the API call is made successfully. The error is after fetching the accounts in fbAPI.accounts().then((accounts) which I think is due to GraphRequestManager returning immediately instead of waiting.
I have a solution for you.
My provider look like this :
FBGraphRequest = async (fields) => {
const accessData = await AccessToken.getCurrentAccessToken();
// Create a graph request asking for user information
return new Promise((resolve, reject) => {
const infoRequest = new GraphRequest('/me', {
accessToken: accessData.accessToken,
parameters: {
fields: {
string: fields
}
}
},
(error, result) => {
if (error) {
console.log('Error fetching data: ' + error.toString());
reject(error);
} else {
resolve(result);
}
});
new GraphRequestManager().addRequest(infoRequest).start();
});
};
triggerGraphRequest = async () => {
let result = await this.FBGraphRequest('id, email');
return result;
}
That works great ! I let you adapt my solution to your system.