react native image uri and async storage - react-native

i'm trying to save a profile picture and i save it with asyncStorage. store part working perfectly but if i close app and reopen it doesn`t show image.
i logging image uri and there is uri but cant solve the problem.
here is my code
this is image pick part
const ImagePick = async () => {
const options = {
title: 'Seçim yapınız.',
cancelButtonTitle: 'İptal',
takePhotoButtonTitle: 'Bir fotoğraf çek',
chooseFromLibraryButtonTitle: 'Galeriden seç',
chooseWhichLibraryTitle: 'Galeriden seç',
mediaType: 'photo',
storageOptions: {skipBackup: true, path: 'images'},
};
let isCameraPermitted = await requestCameraPermission();
let isStoragePermitted = await requestExternalWritePermission();
if (isCameraPermitted && isStoragePermitted) {
ImagePicker.showImagePicker(options, async response => {
//console.log('response', response);
if (response.didCancel) {
console.log('Kullanıcı fotoğraf seçimini iptal etti');
} else if (response.customButton) {
console.log('Özel butona tıklandı.');
} else if (response.error) {
console.log('error', 'Bir hata oluştu.');
} else {
console.log(response.fileName);
let uri = response.uri;
let path = response.uri;
if (Platform.OS === 'ios') {
path = '~' + path.substring(path.indexOf('/Documents'));
}
if (!response.fileName) {
response.fileName = path.split('/').pop();
}
let name = response.fileName;
let type = `image/${name.split('.').slice(-1)[0]}`;
console.log('uri', uri);
console.log('name', name);
console.log('type', type);
setImageUri(response.uri);
try {
await AsyncStorage.setItem('profilePicture', response.uri);
console.log('async storage kayıt başarılı');
} catch (error) {
console.log(error);
}
}
});
}
};
i get image like this
useEffect(() => {
getProfilePicture();
}, []);
const getProfilePicture = async () => {
const profilePicture = await AsyncStorage.getItem('profilePicture');
console.log('profilePicture', profilePicture);
if (profilePicture !== null) {
setImageUri(profilePicture);
setIsLoading(false);
} else {
setImageUri(
'https://t3.ftcdn.net/jpg/03/46/83/96/360_F_346839683_6nAPzbhpSkIpb8pmAwufkC7c5eD7wYws.jpg',
);
setIsLoading(false);
}
};

emulator is the problem. in device it's working

Related

Create VIdeocall room with multiple users using WebRtc and firebase

i am trying to create a room video call something like Whatsapp with firebase as signalisation server for two users it works perfect as expected but when a third user join everything stop working
if the user A the first who join and the user B the second until the user C join everything work fine but when C join user A freeze and lost user B connection and B share screen with C but also sometimes freezing
here is my code
onst joinRoom = async () => {
const roomRef = await firestore().collection('meets').doc(params.callId);
roomRef
.collection('users')
.add({name, type: 'join'})
.then(() => {
roomRef
.collection('users')
.get()
.then(async querySnapshot => {
if (querySnapshot.empty) {
console.log('EMPTY');
} else {
querySnapshot.forEach(async snap => {
if (snap.data().name !== name && snap.data().type === 'join') {
// data.push(snap.data().name);
await creatOffer(snap.data().name);
}
// if (data.length > 0) {
// Promise.all(data).then(async user => {
// return await creatOffer(user);
// });
// }
});
}
});
});
// // listen on any new offers
roomRef.collection('offers').onSnapshot(data => {
data.docChanges().forEach(async change => {
if (change.type === 'added') {
// console.log('changes', change.doc.data());
if (change.doc.data().to === name) {
await createAnswer(change.doc.data().from, change.doc.data().offer);
}
}
});
});
//listen to answers
roomRef.collection('answers').onSnapshot(async snapshot => {
snapshot.docChanges().forEach(async change => {
if (change.type === 'added') {
const pc = pcPeers[change.doc.data().from];
if (change.doc.data().to === name) {
const rtcSessionDescription = new RTCSessionDescription(
change.doc.data().answer,
);
if (pc && rtcSessionDescription) {
await pc.setRemoteDescription(rtcSessionDescription);
}
}
}
});
});
//listen to candidate change
roomRef.collection('candidates').onSnapshot(async snapshot => {
snapshot.docChanges().forEach(async change => {
// console.log('answers', change.doc.data());
if (change.type === 'added') {
console.log('added', Platform.OS);
if (change.doc.data().to === name) {
const pc = pcPeers[change.doc.data().from];
// console.log(pc);
if (pc) {
await pc.addIceCandidate(
new RTCIceCandidate(change.doc.data().candidate),
);
}
}
}
});
});
};
and function to create offer
const creatOffer = async to => {
try {
const {roomRef, localPC} = await initializePeer(to);
const offer = await localPC.createOffer();
// console.log('offer', offer);
if (offer) {
await localPC.setLocalDescription(offer);
await roomRef.collection('offers').add({from: name, to, offer});
}
pcPeers = {...pcPeers, [to]: localPC};
} catch (e) {
console.log(e);
}
};
function to create answer
const createAnswer = async (from, offer) => {
try {
const {localPC, roomRef} = await initializePeer(from);
await localPC.setRemoteDescription(new RTCSessionDescription(offer));
const answer = await localPC.createAnswer();
await localPC.setLocalDescription(answer);
// await checkIfAnswerAlreadyCreated(from, name);
await roomRef.collection('answers').add({from: name, to: from, answer});
pcPeers = {...pcPeers, [from]: localPC};
} catch (e) {
console.log(e);
}
};
and here is how i initialise a peer
setLocalStream(initialStream);
const roomRef = await firestore().collection('meets').doc(params.callId);
const collection = roomRef.collection('candidates');
localPC.onicecandidate = async e => {
if (!e.candidate) {
return;
}
// console.log('canditates', Platform.OS);
const state = localPC.iceGatheringState;
if (state !== 'complete') {
await collection.add({
from: name,
candidate: e.candidate.toJSON(),
to,
date: new Date(),
});
} else {
Alert.alert('tes');
}
// InCallManager.setForceSpeakerphoneOn(true);
// InCallManager.setSpeakerphoneOn(true);
};
localPC.onsignalingstatechange = async event => {
// when the signal state become stable record the data and stop ringback
if (event.target.signalingState === 'stable') {
if (Platform.OS === 'ios') {
localStream?.getVideoTracks().forEach(track => {
//For ios to trigger the camera on
track._switchCamera();
track._switchCamera();
});
}
}
};
localPC.onaddstream = e => {
if (e?.stream) {
// console.log(
// `RemotePC received the stream call ${Platform.OS}_${Platform.Version}`,
// e?.stream,
// );
console.log(Platform.OS, ' ', Platform.Version);
if (remoteStream === null) {
// Alert.alert('stream 1');
setRemoteStream(e?.stream);
} else {
// Alert.alert('stream 2');
setRemoteStream_(e?.stream);
}
}
};
return {localPC, roomRef};
};
can anyone help me with some hints where is tthe problem i’ve created for my self here and thank you

Unhandled promise rejection: TypeError: Network request failed in react native

I am new to react native. I have crated a form. from this form I am uploading images to server. But the problem not a single data uploading to server. So what is problem is my code is wrong or what please help . I am not getting any specific error. please help. thanks. and my other forms is submitting properly they have not any images to upload but only problem with this form becuase here is images to upload
here is my code
export default function Add(props) {
const { navigation } = props
const [singleFilePAN, setSingleFilePAN] = useState('');
const [singleFileADH, setSingleFileADH] = useState('');
const [singleFileADH1, setSingleFileADH1] = useState('');
const [singleFileSIGN, setSingleFileSIGN] = useState('');
const [imageArray, setImageArray] = useState({
PAN: null,
GST: null,
ADH: null,
ADH1: null,
});
const validateInputs = () => {
console.log(singleFilePAN)
console.log(singleFileADH)
console.log(singleFileADH1)
console.log(singleFileSIGN)
if (singleFilePAN && singleFileADH && singleFileADH1 && singleFileSIGN != null)
{
if (!/[A-Z]{5}[0-9]{4}[A-Z]{1}/.test(PAN) && imageArray.GST === null){
setPanError('Please Insert valid PAN Card Image \n And Valid Pan card number')
return;
}
if (!/^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$/.test(GST)) {
setGstError('Please Insert valid GST Number')
return;
}
if (!/^\d{4}\s\d{4}\s\d{4}$/.test(ADH)) {
setAdhError('Please Insert valid Aadhar Card Image \n And Valid Adhar card number')
return;
}
else
{
//+++++++++++++++++++++++++++++++++=submitting form data to api start+++++++++++++++++++++++++++++++++++
{
const leadTagNumber = props.route.params.leadTagNumber
AsyncStorage.multiGet(["application_id", "created_by",'leadTagNumber']).then(response => {
const formData = new FormData();
formData.append('lead_tag_number',leadTagNumber);
formData.append('pan_card_number', PAN);
formData.append('gstin_number', GST);
formData.append('aadhar_card_number', ADH);
formData.append('idfy_pan_card_status', "Done");
formData.append('idfy_aadhar_card_status',"Done");
formData.append('entry_sorce', "App");
formData.append('created_by', response[1][1]);
formData.append('application_id', response[0][1]);
formData.append('is_active', "Y");
formData.append('is_deleted', "N");
formData.append('created_time', "");
formData.append('upload_pancard',
{
uri: singleFilePAN,
name: 'pancardImage.jpg',
type: 'image/jpg/png'
}
);
formData.append('upload_aadhar',
{
uri: singleFileADH,
name: 'upload_aadhar.jpg',
type: 'image/jpg/png'
}
);
formData.append('upload_aadhar_second',
{
uri: singleFileADH1,
name: 'upload_aadhar_second.jpg',
type: 'image/jpg/png'
}
);
formData.append('digital_signature',
{
uri: singleFileSIGN,
name: 'digital_signature.jpg',
type: 'image/jpg/png'
}
);
fetch('https://nasdigital.tech/Android_API_CI/upload_multipart_data', {
method: 'POST',
headers: {'Accept': 'application/json, text/plain, */*', "Content-Type": "application/json" },
body: formData
})
.then((returnValue) => returnValue.json())
.then(function(response) {
console.log(response)
Alert.alert("File uploaded");
return response.json();
});
});
// event.preventDefault();
}
//+++++++++++++++++++++++++++++++++submitting form data to api end++++++++++++++++++++++++++++++++++++++
Alert.alert("success")
return;
}
}
};
const takePicture = async (type) => {
if (camera) {
const data = await camera.takePictureAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
});
console.log(data.uri);
const newImageArr = imageArray;
if (imageType === 'PAN') {
newImageArr.PAN = data.uri;
}else if (imageType === 'ADH' && evenTry) {
newImageArr.ADH = data.uri;
setEvenTry((val) => !val);
} else if (imageType === 'ADH' && !evenTry) {
newImageArr.ADH1 = data.uri;
setEvenTry((val) => !val);
}
setImageArray({...newImageArr});
setShowCamera(false);
setImageType('');
setSingleFilePAN({ singleFilePAN: newImageArr.PAN});
setSingleFileADH({ singleFileADH: newImageArr.ADH});
setSingleFileADH1({ singleFileADH1: newImageArr.ADH1});
}
};
const pickImage = async (type) => {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
});
console.log(result.uri);
if (!result.cancelled) {
const newImageArr = imageArray;
if (type === 'PAN') {
newImageArr.PAN = result.uri;
} else if (type === 'ADH' && evenTry) {
newImageArr.ADH = result.uri;
setEvenTry((val) => !val);
} else if (type === 'ADH' && !evenTry) {
newImageArr.ADH1 = result.uri;
setEvenTry((val) => !val);
}
setImageArray({ ...newImageArr });
setSingleFilePAN({ singleFilePAN: newImageArr.PAN});
setSingleFileADH({ singleFileADH: newImageArr.ADH});
setSingleFileADH1({ singleFileADH1: newImageArr.ADH1});
}
please ignore this = I am new to react native. I have crated a form. from this form I am uploading images to server. But the problem not a single data uploading to server. So what is problem is my code is wrong or what please help . I am not getting any specific error. please help. thanks
I think you have a bad type of form data passed with image, if you won't pass type of data you want to send BE probably won't get it
instead of
{
uri: singleFilePAN,
name: 'pancardImage.jpg', <- don't add extenstion
type: 'image/jpg/png' <- bad type
}
{
uri: singleFilePAN,
name: 'pancardImage',
type: 'image/jpg'
}
check all mime types here -> MIME DOCS

Using AsyncStorage to show screen on first login

I'm trying to only show the disclosure screen the first time the user logs in by using AsyncStorage. Currently getData is returning a Promise and it goes straight to the landing screen on first login.
Could I get some help to get this functioning the way I want it to?
This is my login handler:
const key = 'key';
const storeData = async () => {
try {
await AsyncStorage.setItem('key', 'true');
} catch (error) {
// saving failed
console.log(error.message);
}
};
const getData = async key => {
let value = '';
try {
value = await AsyncStorage.getItem(key);
return JSON.parse(value);
} catch (e) {
console.log(error.message);
}
};
const _loginHandler = () => {
if (userName == '' || password == '') {
console.log('gagagagagagagagagagagagagagagagag');
} else {
setShowLoading(true);
const payload = {userName: userName.trim(), password: password.trim()};
setUserName('');
setPassword('');
_UserLoginHandler(payload).then(data => {
setShowLoading(false);
if (data.error) {
GlobalShowSnackBar(data.error);
} else {
setTimeout(() => {
setUserId(data);
//props.navigation.replace(getData("key")?'Landing':'Disclosure')
console.log('Key Value ' + JSON.stringify(getData('key'))); <-- this outputs Key Value {"_U":0,"_V":0,"_W":null,"_X":null}
if (getData('key')) {
props.navigation.navigate('Landing');
} else {
storeData(key);
props.navigation.navigate('Disclosure');
}
}, 500);
}
});
}
};
I got it to work with
getData('key').then(val => {
if (val) {
props.navigation.navigate('Landing');
} else {
storeData(key);
props.navigation.navigate('Disclosure');
}
});

In react-native-share on ios we need to know why share options pop up screens getting dismissed immediately?

composeEmail = async () => {
const file = await this.downloadCsv();
const res = await RNFetchBlob.fs.exists(file.path);
if (res) {
const data = await RNFetchBlob.fs.readFile(file.path, 'base64');
console.log("encoded data", data)
if (Platform.OS === "ios") {
const shareOptions = {
social: Share.Social.EMAIL,
subject: '',
filename: file.filename.split(".")[0],
saveToFiles: file.path,
url: file.path,
type: 'csv',
failOnCancel: true,
}
try {
const ShareResponse = await Share.shareSingle(shareOptions);
} catch (error) {
console.log('Error:', error)
}
}
In that when we click on share button pop up the share screen but dismissed immediately.for that we also use Share.open(ShareOptions) but same result found.

React native asyncstorage cannot get data

I'm starting my react-native project with npm start. On my emulator I have installed expo to view my application. Also I'm using http://ip:19001/debugger-ui/ to debug my application in google chrome.
I don't know what I'm doing wrong but I can't get any data from asyncstorage. Can you please give me some tips how to correct this problem.
In one of my activities I store data with;
storeDataInAsync1(idSchool,year) {
try {
//await AsyncStorage.removeItem('user');
AsyncStorage.setItem('dateRange', this.props.range);
AsyncStorage.setItem('idSchool', idSchool);
AsyncStorage.setItem('school_year', year);
} catch (error) {
// Error saving data
}
}
My call to this method;
async saveMyProfil() {
var formData = new FormData();
formData.append('id_school',this.props.idSchool);
formData.append('school_year', this.props.year);
await fetch(`${api.url}/my_profile/`, {
method: 'POST',
headers: {
"Content-Type": "multipart/form-data"
},
body: formData,
}).then((response) => response.json())
.then((json) => {
console.log('Response: ' + JSON.stringify(json));
this.storeDataInAsync1(json.id_school,json.school_year);
//_storeData(json.id_school,json.school_year);
//this.doStuff(json.id_school,json.school_year);
})
.catch((error) => {
});
}
back() {
//this.storeDataInAsync();
this.saveMyProfil();
this.props.navigation.goBack();
}
In another activity there is method to retrive data;
_retrieveData = async () => {
try {
const value = await AsyncStorage.getItem('idSchool');
const year = await AsyncStorage.getItem('school_year');
if (value !== null && year !== null) {
// We have data!!
console.log('Id School: ' + value);
console.log('Year: ' + year);
}
} catch (error) {
// Error retrieving data
}
}
I call _retrieveData in;
componentDidMount() {
BackHandler.addEventListener('hardwareBackPress', this.handleBackButton);
this._retrieveData();
}