Uploading image to AWS S3 - react-native

i am a beginner in react native. my problem is, i am trying to send image from camera to aws s3. this is my latest code.
import React from 'react';
import { StyleSheet, Text, View, TouchableOpacity, Button, Image } from 'react-native';
import ImagePicker from 'react-native-image-picker';
import { RNS3 } from 'react-native-aws3';
import fs from 'react-native-fs';
import Buffer from 'buffer';
import AWS from 'aws-sdk';
function uploadToS3(image){
const filename = "the_file.jpeg";
const options = {
keyPrefix: "uploads/",
bucket: "this is bucketname",
region: "this is region",
accessKey: "this is access key",
secretKey: "this is secret key",
successActionStatus: 201
}
try{
const s3 = new AWS.S3({accessKeyId: options.accessKey, secretAccessKey:options.secretKey, region:options.region});
var UploadURL;
const params = {Bucket: options.bucket, Key: options.keyPrefix+filename, ContentType: image.type};
s3.getSignedUrl('putObject', params, function (err, url) {
console.log('Your generated pre-signed URL is', url);
UploadURL = url;
const xhr = new XMLHttpRequest()
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log("ok: ", xhr.response);
alert("success");
} else {
console.log("no: " , xhr.response);
alert("no");
}
}
}
xhr.open('PUT', UploadURL)
xhr.setRequestHeader('Content-Type', image.type)
xhr.send({image})
});
} catch(error){
console.log("err : ",error)
}
}
class HomeScreen extends React.Component {
constructor(props) {
global.currentScreenIndex = 'HomeScreen';
super(props);
this.state = {
resourcePath: {},
requestStatus: {},
employees: {},
response: {},
};
}
cameraLaunch = (id) => {
console.log(id);
let options = {
title: 'Select Picture',
storageOptions: {
skipBackup: true,
path: 'images',
},
base64: true,
maxWidth: 400,
maxHeight: 400
};
ImagePicker.launchCamera(options, (res) => {
//console.log('Response = ', res);
if (res.didCancel) {
console.log('User cancelled image picker');
} else if (res.error) {
console.log('ImagePicker Error: ', res.error);
} else if (res.customButton) {
console.log('User tapped custom button: ', res.customButton);
alert(res.customButton);
} else {
let source = res;
this.setState({
resourcePath: source,
});
uploadToS3(res);
}
});
}
render(){
return (
<View style={{ flex: 1, alignItems: 'center', marginTop: 100 }}>
<Button
onPress={()=>this.cameraLaunch(1)}
title="OpenCamera"
color="#841584"
/>
<Text style={{ alignItems: 'center' }}>
{this.state.resourcePath.uri}
</Text>
<Image source={this.state.resourcePath} />
</View>
);
}
};
export default HomeScreen;
there is nothing wrong with the camera or presigned url generation. if run, there will be the_file.jpeg in "this is bucket name"/uploads/the_file.jpeg, but the problem is, its size is 0 byte. i have tried to send just image.data, but apparently it just make the_file.jpeg become a "txt file" with "jpeg" extension. please help.
ps : i am aware on how insecure this code.

It looks like you missed the purpose of presigned URLs which is to upload objects without the need of AWS credentials. In your example, you are initializing the S3 client using the AWS credential, in that case, you can simply use s3.upload function to upload your file.

I had the same issue and nothing helped. This is what I did.
Make sure you follow the amplify guide for setting up a app. amplify init, amplify add auth, amplify push, and then amplify add storage and then do this.
import Amplify, { Storage } from 'aws-amplify'
import config from './src/aws-exports'
// import awsconfig from './aws-exports';
// Might need to switch line 7 to awsconfig
Amplify.configure(config)
import { StatusBar } from 'expo-status-bar';
import React, { useState, useEffect } from 'react';
import { Button, Image, View, Platform, StyleSheet, Text, TextInput } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
function App() {
const [image, setImage] = useState(null)
const [name, setName] = useState('Evan Erickson')
useEffect(() => {
(async () => {
if (Platform.OS !== 'web') {
const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
if (status !== 'granted') {
alert('Sorry, we need camera roll permissions to make this work!');
}
}
})();
}, []);
const pickImage = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
console.log(result)
async function pathToImageFile(data) {
try {
const response = await fetch(data);
const blob = await response.blob();
await Storage.put(`customers/${name}`, blob, {
contentType: 'image/jpeg', // contentType is optional
});
} catch (err) {
console.log('Error uploading file:', err);
}
}
// later
pathToImageFile(result.uri);
}
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Button title="Pick an image from camera roll" onPress={pickImage} />
{image && <Image source={{ uri: image }} style={{ width: 200, height: 200 }} />}
<Button title="Upload image" onPress={() => {alert(image)}} />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
export default withAuthenticator(App)

Related

Issue sending & receiving streams between two clients in LiveKit's React Native SDK

I'm trying to build on the example app provided by livekit, so far I've implemented everything like the example app and I've been successful with connecting to a room on example website, I recieve audio from website, but I don't read the video stream, and I also can't send audio or video at all.
Steps to reproduce the behavior:
add the following to index.js
import { registerRootComponent } from "expo";
import { registerGlobals } from "livekit-react-native";
import App from "./App";
registerRootComponent(App);
registerGlobals();
Rendering the following component in App.tsx
import { Participant, Room, Track } from "livekit-client";
import {
useRoom,
useParticipant,
AudioSession,
VideoView,
} from "livekit-react-native";
import { useEffect, useState } from "react";
import { Text, ListRenderItem, StyleSheet, FlatList, View } from "react-native";
import { ParticipantView } from "./ParticipantView";
import { RoomControls } from "./RoomControls";
import type { TrackPublication } from "livekit-client";
const App = () => {
// Create a room state
const [, setIsConnected] = useState(false);
const [room] = useState(
() =>
new Room({
publishDefaults: { simulcast: false },
adaptiveStream: true,
})
);
// Get the participants from the room
const { participants } = useRoom(room);
const url = "[hard-coded-url]";
const token =
"[hard-coded-token";
useEffect(() => {
let connect = async () => {
// If you wish to configure audio, uncomment the following:
await AudioSession.configureAudio({
android: {
preferredOutputList: ["speaker"],
},
ios: {
defaultOutput: "speaker",
},
});
await AudioSession.startAudioSession();
await room.connect(url, token, {});
await room.localParticipant.setCameraEnabled(true);
await room.localParticipant.setMicrophoneEnabled(true);
await room.localParticipant.enableCameraAndMicrophone();
console.log("connected to ", url);
setIsConnected(true);
};
connect();
return () => {
room.disconnect();
AudioSession.stopAudioSession();
};
}, [url, token, room]);
// Setup views.
const stageView = participants.length > 0 && (
<ParticipantView participant={participants[0]} style={styles.stage} />
);
const renderParticipant: ListRenderItem<Participant> = ({ item }) => {
return (
<ParticipantView participant={item} style={styles.otherParticipantView} />
);
};
const otherParticipantsView = participants.length > 0 && (
<FlatList
data={participants}
renderItem={renderParticipant}
keyExtractor={(item) => item.sid}
horizontal={true}
style={styles.otherParticipantsList}
/>
);
const { cameraPublication, microphonePublication } = useParticipant(
room.localParticipant
);
return (
<View style={styles.container}>
{stageView}
{otherParticipantsView}
<RoomControls
micEnabled={isTrackEnabled(microphonePublication)}
setMicEnabled={(enabled: boolean) => {
room.localParticipant.setMicrophoneEnabled(enabled);
}}
cameraEnabled={isTrackEnabled(cameraPublication)}
setCameraEnabled={(enabled: boolean) => {
room.localParticipant.setCameraEnabled(enabled);
}}
onDisconnectClick={() => {
// navigation.pop();
console.log("disconnected");
}}
/>
</View>
);
};
function isTrackEnabled(pub?: TrackPublication): boolean {
return !(pub?.isMuted ?? true);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: "center",
justifyContent: "center",
},
stage: {
flex: 1,
width: "100%",
},
otherParticipantsList: {
width: "100%",
height: 150,
flexGrow: 0,
},
otherParticipantView: {
width: 150,
height: 150,
},
});
export default App;
the components used here are mostly the same as what's in the example, I've removed the screensharing logic and the messages
5. I run the app using an expo development build
6. it will log that it's connected, you'll be able to hear sound from the remote participant, but not see any video or send any sound.
7. if i try to add
await room.localParticipant.enableCameraAndMicrophone();
in the useEffect, I get the following error:
Possible Unhandled Promise Rejection (id: 0):
Error: Not implemented.
getSettings#http://192.168.1.150:8081/index.bundle?platform=ios&dev=true&hot=false:103733:24
#http://192.168.1.150:8081/index.bundle?platform=ios&dev=true&hot=false:120307:109
generatorResume#[native code]
asyncGeneratorStep#http://192.168.1.150:8081/index.bundle?platform=ios&dev=true&hot=false:21908:26
_next#http://192.168.1.150:8081/index.bundle?platform=ios&dev=true&hot=false:21927:29
#http://192.168.1.150:8081/index.bundle?platform=ios&dev=true&hot=false:21932:14
tryCallTwo#http://192.168.1.150:8081/index.bundle?platform=ios&dev=true&hot=false:26656:9
doResolve#http://192.168.1.150:8081/index.bundle?platform=ios&dev=true&hot=false:26788:25
Promise#http://192.168.1.150:8081/index.bundle?platform=ios&dev=true&hot=false:26675:14
#http://192.168.1.150:8081/index.bundle?platform=ios&dev=true&hot=false:21924:25
#http://192.168.1.150:8081/index.bundle?platform=ios&dev=true&hot=false:120173:52
generatorResume#[native code]
asyncGeneratorStep#http://192.168.1.150:8081/index.bundle?platform=ios&dev=true&hot=false:21908:26
_next#http://192.168.1.150:8081/index.bundle?platform=ios&dev=true&hot=false:21927:29
tryCallOne#http://192.168.1.150:8081/index.bundle?platform=ios&dev=true&hot=false:26648:16
#http://192.168.1.150:8081/index.bundle?platform=ios&dev=true&hot=false:26729:27
#http://192.168.1.150:8081/index.bundle?platform=ios&dev=true&hot=false:27687:26
_callTimer#http://192.168.1.150:8081/index.bundle?platform=ios&dev=true&hot=false:27602:17
_callReactNativeMicrotasksPass#http://192.168.1.150:8081/index.bundle?platform=ios&dev=true&hot=false:27635:17
callReactNativeMicrotasks#http://192.168.1.150:8081/index.bundle?platform=ios&dev=true&hot=false:27799:44
__callReactNativeMicrotasks#http://192.168.1.150:8081/index.bundle?platform=ios&dev=true&hot=false:21006:46
#http://192.168.1.150:8081/index.bundle?platform=ios&dev=true&hot=false:20806:45
__guard#http://192.168.1.150:8081/index.bundle?platform=ios&dev=true&hot=false:20986:15
flushedQueue#http://192.168.1.150:8081/index.bundle?platform=ios&dev=true&hot=false:20805:21
flushedQueue#[native code]
Expected behavior
This should both receive & send video and audio streams between the two clients

trigger fetching and updating parent data from separated component using userContext in react native

enter image description here
Above is the image description of what I want to achieve. I already implemented all the layers but I have a problem in automatically updating userContext. I have to refresh the userContext.js page manually to all the information across the app get updated as I want.
My DataBase.js looks like this
import React, { createContext, useState, useEffect,useCallback} from "react";
// create context
const UserContext = createContext();
const UserContextProvider = ({children}) => {
// the value that will be given to the context
var data = global.userSignedUp
const [UserDetails, SetUserDetails] = useState(data)
const [loadingUser, setLoadingUser] = useState(true);
// fetch a user from a fake backend API
const fetchUser = async () => {
// this would usually be your own backend, or localStorage
// for example
var name = global.userSignedUp.username
var index= global.userSignedUp.id
console.log('This the response from DataBase.js',UserDetails)
const data= await fetch('XXXXXX/api/userprofile/'+UserDetails.id+'/',{
method : 'GET',
header : {
Accept : 'application/json',
'Content-Type' : 'application/json'
}
}).then(async res =>{
const response =await res.json()
console.log('This the response from DataBase.js',response)
SetUserDetails(response)
})
//
};
useEffect(() => {
fetchUser();
}, []);
return (
// the Provider gives access to the context to its children
<UserContext.Provider value={[UserDetails, SetUserDetails]}>
{children }
</UserContext.Provider>
);
};
export { UserContext, UserContextProvider };
I defined one global variable index that get updated depending on the user ID from the sign in page and passed inside the Database.js
const onSignInPressed =(logindata)=>{
const username = logindata.username
const password =logindata.password
// state={
// credentials :{username : username, password: password}
// }
fetch('http://XXXXX/auth/',{
method:'POST',
headers:{'Content-Type':'application/json'},
body : JSON.stringify({username:username, password:password})
}).then (async data =>{
const DataResponse =await data.json()
//console.log(DataResponse)
if (data.status===200){
fetch('http://XXXX/api/userprofile',{
method : 'GET',
header : {
Accept : 'application/json',
'Content-Type' : 'application/json'
}
}).then(async res =>{
const response =await res.json()
for (let i=0; i < response.length;i++){
if (response[i].user=== username){
userSignedUp=response[i]
console.log('this is the user Signed up Id',userSignedUp)
navigation.navigate('HomeProfile')
;
}
}
})
}
else{
Alert.alert('Invalid User!','Username or password is incorrect,')
}
})
}
in my HomeProfile.js I can get all the data from UserContext and it workds fine.
Now in my EditProfile.js I have this :
import React , {useState,useContext,useEffect,useCallback} from 'react'
import {SocialIcon} from 'react-native-elements'
import { ImageBackground, View, Text, Image, StyleSheet, useWindowDimensions,Alert} from 'react-native'
import { icons,images, COLORS, SIZES } from '../constants';
import {CustomInput} from '../Component/CustomInput';
import CustomButton from '../Component/CustomButton';
import {useNavigation} from '#react-navigation/native';
import {useForm, Controller} from 'react-hook-form';
import { UserContext, UserContextProvider } from "./MobileDatabase/DataBase";
const EditProfile = () => {
return (
<UserContextProvider>
<EditProfilePage />
</UserContextProvider>
);
}
const EditProfilePage = () => {
const {control,handleSubmit,watch} = useForm();
const {height}= useWindowDimensions();
const navigation =useNavigation();
const newpwd = watch('NewPassword')
const [UserDetails, SetUserDetails]= useContext(UserContext);
let OldUsername=UserDetails.user
let DataFromServer=UserDetails
const onSavePressed = async (EditData) =>{
console.log(EditData)
const uploadData =new FormData();
uploadData.append('username',EditData.ChangeUsername)
let editData= await fetch('http://192.168.56.1:8000/api/users/'+OldUsername+'/',{
method:'PATCH',
headers:{Accept: 'application/json',
'Content-Type': 'multipart/form-data; '},
body :uploadData,
})
let EditDataResponseJson = await editData.json();
console.log(EditDataResponseJson)
SetUserDetails({...UserDetails, user:EditDataResponseJson.username})
UserContextProvider(EditDataResponseJson)
navigation.navigate('HomeProfile')
}
return (
<View style={styles.root}>
<Image
source ={{uri:UserDetails.Profileimage}}
style={[styles.logo]}
//resizeMode='contain'
/>
<Text style={{fontWeight:'bold',
//position:"absolute",
flex:1,
fontSize: 20,
top:'3%',
maxWidth:200,
alignSelf:'center' }}>{UserDetails.user}</Text>
<CustomInput placeholder ='Change UserName'
name="ChangeUsername"
control={control}
rules={{required: 'Username is required',
minLength:{
value:3,
message :'Username should be at least 3 characters long'
}
}}
// value={username}
// setValue={setUsername}
/>
<CustomInput placeholder= 'Change Password'
name ='NewPassword'
control={control}
rules={{required: 'New password is required'}}
// value={password}
// setValue={setPassword}
secureTextEntry={true}
/>
<CustomInput placeholder= 'Confirm Password'
name ='RepeatNewPassword'
control={control}
rules={{
validate: value => value === newpwd || 'Password do not match'
}}
// value={password}
// setValue={setPassword}
secureTextEntry={true}
/>
<View style ={styles.Signup}>
<CustomButton text= 'Save Changes' onPress={handleSubmit(onSavePressed)} />
</View>
</View>
)
}
const styles = StyleSheet.create({
root :{
//alignItems :'center',
paddingTop :'60%',
flex: 1,
},
cover:{
flex:1,
justifyContent: 'center',
},
logo:{
position :'absolute',
top:'10%',
alignSelf:'center',
justifyContent:'center',
alignItems: 'center',
width: 150,
height: 150,
borderRadius: 400/ 2,
},
Signup:{
marginTop: '20%',
}
})
export default EditProfile
When I update the Username for example, it only changes inside EditPage.js but not in HomeProfile.js event thought I update the SetUserDetails. The only way to see the updated data is to refresh the Database.js.
I am very much stuck since a month now and hope for a help here.
Thank you!!

React native image picker not displaying selected image

I don't seem to be able to render the image selected when using react-native-image-picker. After selecting an image from the device library the default image stays selected
My first thoughts are it has something to do with the path
defaultImageUri http://localhost:8081/assets/src/assets/images/emptyavatar.jpg?platform=ios&hash=54674069799117e0326e575845f59679
imageURI file:///Users/lewisr66/Library/Developer/CoreSimulator/Devices/CA90AEB9-E017-4E46-9D5F-A4761F060334/data/Containers/Data/Application/71492FA8-D8D3-4CC5-B810-E64EC1C08C6A/tmp/999D74FB-BCE6-46BC-AAF3-0A81FEFDB3F0.jpg
But I'm unsure it this has anything to do with it. Have I done something wrong here?
import React, {useContext, useState} from 'react';
import {Image} from 'react-native';
import {Avatar} from 'native-base';
import defaultProfileImage from '../../assets/images/emptyavatar.jpg';
import {launchImageLibrary} from 'react-native-image-picker';
export const UserProfile = () => {
// Image Picker
const defaultImageUri = Image.resolveAssetSource(defaultProfileImage).uri;
const [imageURI, setImageURI] = useState(defaultImageUri);
const options = {
title: 'Select Image',
type: 'library',
options: {
maxHeight: 200,
maxWidth: 200,
selectionLimit: 1,
mediaType: 'photo',
includeBase64: false,
},
};
const openGallery = async () => {
const imageData = await launchImageLibrary(options);
setImageURI(imageData.assets[0].uri);
};
return (
<Avatar source={{uri: imageURI}} w="24" h="24" />
);
}
Try something like this:-
const handleOpenLibrary = () => {
let options = {
mediaType: "photo",
//rest your options
};
launchImageLibrary(options, (response) => {
if (response.didCancel) {
} else if (response.error) {
} else if (response.customButton) {
Alert.alert(response.customButton);
} else {
let source = response;
console.log("source", source);
let imageSizeInKb = source.fileSize / 1024
let imageSizeInMb = imageSizeInKb / 1024
if (imageSizeInMb < 10) {
setImageURI(source.uri)
}
else {
Toast.show({
text1: "AppName",
text2: "size error",
type: "error",
position: "top"
});
}
}
});
};
And in return:-
<View style={{flex:1}}>
<Image
source={{uri:imageURI}}
style={{height:50,width:50}}/>
</View>

Geolocation clearWatch(watchId) does not stop location tracking (React Native)

I'm trying to create simple example of location tracker and I'm stuck with following case. My basic goal is to toggle location watch by pressing start/end button. I'm doing separation of concerns by implementing custom react hook which is then used in App component:
useWatchLocation.js
import {useEffect, useRef, useState} from "react"
import {PermissionsAndroid} from "react-native"
import Geolocation from "react-native-geolocation-service"
const watchCurrentLocation = async (successCallback, errorCallback) => {
if (!(await PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION))) {
errorCallback("Permissions for location are not granted!")
}
return Geolocation.watchPosition(successCallback, errorCallback, {
timeout: 3000,
maximumAge: 500,
enableHighAccuracy: true,
distanceFilter: 0,
useSignificantChanges: false,
})
}
const stopWatchingLocation = (watchId) => {
Geolocation.clearWatch(watchId)
// Geolocation.stopObserving()
}
export default useWatchLocation = () => {
const [location, setLocation] = useState()
const [lastError, setLastError] = useState()
const [locationToggle, setLocationToggle] = useState(false)
const watchId = useRef(null)
const startLocationWatch = () => {
watchId.current = watchCurrentLocation(
(position) => {
setLocation(position)
},
(error) => {
setLastError(error)
}
)
}
const cancelLocationWatch = () => {
stopWatchingLocation(watchId.current)
setLocation(null)
setLastError(null)
}
const setLocationWatch = (flag) => {
setLocationToggle(flag)
}
// execution after render when locationToggle is changed
useEffect(() => {
if (locationToggle) {
startLocationWatch()
} else cancelLocationWatch()
return cancelLocationWatch()
}, [locationToggle])
// mount / unmount
useEffect(() => {
cancelLocationWatch()
}, [])
return { location, lastError, setLocationWatch }
}
App.js
import React from "react"
import {Button, Text, View} from "react-native"
import useWatchLocation from "./hooks/useWatchLocation"
export default App = () => {
const { location, lastError, setLocationWatch } = useWatchLocation()
return (
<View style={{ margin: 20 }}>
<View style={{ margin: 20, alignItems: "center" }}>
<Text>{location && `Time: ${new Date(location.timestamp).toLocaleTimeString()}`}</Text>
<Text>{location && `Latitude: ${location.coords.latitude}`}</Text>
<Text>{location && `Longitude: ${location.coords.longitude}`}</Text>
<Text>{lastError && `Error: ${lastError}`}</Text>
</View>
<View style={{ marginTop: 20, width: "100%", flexDirection: "row", justifyContent: "space-evenly" }}>
<Button onPress={() => {setLocationWatch(true)}} title="START" />
<Button onPress={() => {setLocationWatch(false)}} title="STOP" />
</View>
</View>
)
}
I have searched multiple examples which are online and code above should work. But the problem is when stop button is pressed location still keeps getting updated even though I invoke Geolocation.clearWatch(watchId).
I wrapped Geolocation calls to handle location permission and other possible debug stuff. It seems like watchId value that is saved using useRef hook inside useWatchLocation is invalid. My guess is based on attempting to call Geolocation.stopObserving() right after Geolocation.clearWatch(watchId). Subscription stops but I get warning:
Called stopObserving with existing subscriptions.
So I assume that original subscription was not cleared.
What am I missing/doing wrong?
EDIT: I figured out solution. But since isMounted pattern is generally considered antipattern: Does anyone have a better solution?
Ok, problem solved with isMounted pattern. isMounted.current is set at locationToggle effect to true and inside cancelLocationWatch to false:
const isMounted = useRef(null)
...
useEffect(() => {
if (locationToggle) {
isMounted.current = true // <--
startLocationWatch()
} else cancelLocationWatch()
return () => cancelLocationWatch()
}, [locationToggle])
...
const cancelLocationWatch = () => {
stopWatchingLocation(watchId.current)
setLocation(null)
setLastError(null)
isMounted.current = false // <--
}
And checked at mount / unmount effect, success and error callback:
const startLocationWatch = () => {
watchId.current = watchCurrentLocation(
(position) => {
if (isMounted.current) { // <--
setLocation(position)
}
},
(error) => {
if (isMounted.current) { // <--
setLastError(error)
}
}
)
}

The best way of tracking location in background using react-native + Expo in 2020

I want to create my own Endomono/Runtastic-like app using RN + expo (This app will be just for me, and I have android phone with pretty decent performance/battery life (Redmi note 7) so I don't worry about performance too much). I wanted to use all-in-one library for that, or just and library that allows me to execute some code each X seconds in background (and getAsyncLocation there). My point is just to send lat/lon data every X seconds to my backend HTTP django-rest-framework powered server.
I just spent whole day trying figure out any way to do that, I tried couple of libraries like this ones: react-native-background-geolocation, react-native-background-timer, react-native-background-job and few more. I followed step by step instalation guide, and I kept getting errors like: null is not an object (evaluating 'RNBackgroundTimer.setTimeout') .
I also tried this: I fixed some errors in this code (imports related), it seemed to work, but when I changed my GPS location using Fake GPS, and only one cast of didFocus functions appears in the console. Here's code:
import React from 'react';
import { EventEmitter } from 'fbemitter';
import { NavigationEvents } from 'react-navigation';
import { AppState, AsyncStorage, Platform, StyleSheet, Text, View, Button } from 'react-native';
import MapView from 'react-native-maps';
import * as Permissions from 'expo-permissions';
import * as Location from 'expo-location';
import * as TaskManager from 'expo-task-manager';
import { FontAwesome, MaterialIcons } from '#expo/vector-icons';
const STORAGE_KEY = 'expo-home-locations';
const LOCATION_UPDATES_TASK = 'location-updates';
const locationEventsEmitter = new EventEmitter();
export default class MapScreen extends React.Component {
static navigationOptions = {
title: 'Background location',
};
mapViewRef = React.createRef();
state = {
accuracy: 4,
isTracking: false,
showsBackgroundLocationIndicator: false,
savedLocations: [],
initialRegion: null,
error: null,
};
didFocus = async () => {
console.log("Hello")
let { status } = await Permissions.askAsync(Permissions.LOCATION);
if (status !== 'granted') {
AppState.addEventListener('change', this.handleAppStateChange);
this.setState({
error:
'Location permissions are required in order to use this feature. You can manually enable them at any time in the "Location Services" section of the Settings app.',
});
return;
} else {
this.setState({ error: null });
}
const { coords } = await Location.getCurrentPositionAsync();
console.log(coords)
const isTracking = await Location.hasStartedLocationUpdatesAsync(LOCATION_UPDATES_TASK);
const task = (await TaskManager.getRegisteredTasksAsync()).find(
({ taskName }) => taskName === LOCATION_UPDATES_TASK
);
const savedLocations = await getSavedLocations();
const accuracy = (task && task.options.accuracy) || this.state.accuracy;
this.eventSubscription = locationEventsEmitter.addListener('update', locations => {
this.setState({ savedLocations: locations });
});
if (!isTracking) {
alert('Click `Start tracking` to start getting location updates.');
}
this.setState({
accuracy,
isTracking,
savedLocations,
initialRegion: {
latitude: coords.latitude,
longitude: coords.longitude,
latitudeDelta: 0.004,
longitudeDelta: 0.002,
},
});
};
handleAppStateChange = nextAppState => {
if (nextAppState !== 'active') {
return;
}
if (this.state.initialRegion) {
AppState.removeEventListener('change', this.handleAppStateChange);
return;
}
this.didFocus();
};
componentWillUnmount() {
if (this.eventSubscription) {
this.eventSubscription.remove();
}
AppState.removeEventListener('change', this.handleAppStateChange);
}
async startLocationUpdates(accuracy = this.state.accuracy) {
await Location.startLocationUpdatesAsync(LOCATION_UPDATES_TASK, {
accuracy,
showsBackgroundLocationIndicator: this.state.showsBackgroundLocationIndicator,
});
if (!this.state.isTracking) {
alert(
'Now you can send app to the background, go somewhere and come back here! You can even terminate the app and it will be woken up when the new significant location change comes out.'
);
}
this.setState({ isTracking: true });
}
async stopLocationUpdates() {
await Location.stopLocationUpdatesAsync(LOCATION_UPDATES_TASK);
this.setState({ isTracking: false });
}
clearLocations = async () => {
await AsyncStorage.setItem(STORAGE_KEY, JSON.stringify([]));
this.setState({ savedLocations: [] });
};
toggleTracking = async () => {
await AsyncStorage.removeItem(STORAGE_KEY);
if (this.state.isTracking) {
await this.stopLocationUpdates();
} else {
await this.startLocationUpdates();
}
this.setState({ savedLocations: [] });
};
onAccuracyChange = () => {
const next = Location.Accuracy[this.state.accuracy + 1];
const accuracy = next ? Location.Accuracy[next] : Location.Accuracy.Lowest;
this.setState({ accuracy });
if (this.state.isTracking) {
// Restart background task with the new accuracy.
this.startLocationUpdates(accuracy);
}
};
toggleLocationIndicator = async () => {
const showsBackgroundLocationIndicator = !this.state.showsBackgroundLocationIndicator;
this.setState({ showsBackgroundLocationIndicator }, async () => {
if (this.state.isTracking) {
await this.startLocationUpdates();
}
});
};
onCenterMap = async () => {
const { coords } = await Location.getCurrentPositionAsync();
const mapView = this.mapViewRef.current;
if (mapView) {
mapView.animateToRegion({
latitude: coords.latitude,
longitude: coords.longitude,
latitudeDelta: 0.004,
longitudeDelta: 0.002,
});
}
};
renderPolyline() {
const { savedLocations } = this.state;
if (savedLocations.length === 0) {
return null;
}
return (
<MapView.Polyline
coordinates={savedLocations}
strokeWidth={3}
strokeColor={"black"}
/>
);
}
render() {
if (this.state.error) {
return <Text style={styles.errorText}>{this.state.error}</Text>;
}
if (!this.state.initialRegion) {
return <NavigationEvents onDidFocus={this.didFocus} />;
}
return (
<View style={styles.screen}>
<MapView
ref={this.mapViewRef}
style={styles.mapView}
initialRegion={this.state.initialRegion}
showsUserLocation>
{this.renderPolyline()}
</MapView>
<View style={styles.buttons} pointerEvents="box-none">
<View style={styles.topButtons}>
<View style={styles.buttonsColumn}>
{Platform.OS === 'android' ? null : (
<Button style={styles.button} onPress={this.toggleLocationIndicator} title="background/indicator">
<Text>{this.state.showsBackgroundLocationIndicator ? 'Hide' : 'Show'}</Text>
<Text> background </Text>
<FontAwesome name="location-arrow" size={20} color="white" />
<Text> indicator</Text>
</Button>
)}
</View>
<View style={styles.buttonsColumn}>
<Button style={styles.button} onPress={this.onCenterMap} title="my location">
<MaterialIcons name="my-location" size={20} color="white" />
</Button>
</View>
</View>
<View style={styles.bottomButtons}>
<Button style={styles.button} onPress={this.clearLocations} title="clear locations">
Clear locations
</Button>
<Button style={styles.button} onPress={this.toggleTracking} title="start-stop tracking">
{this.state.isTracking ? 'Stop tracking' : 'Start tracking'}
</Button>
</View>
</View>
</View>
);
}
}
async function getSavedLocations() {
try {
const item = await AsyncStorage.getItem(STORAGE_KEY);
return item ? JSON.parse(item) : [];
} catch (e) {
return [];
}
}
if (Platform.OS !== 'android') {
TaskManager.defineTask(LOCATION_UPDATES_TASK, async ({ data: { locations } }) => {
if (locations && locations.length > 0) {
const savedLocations = await getSavedLocations();
const newLocations = locations.map(({ coords }) => ({
latitude: coords.latitude,
longitude: coords.longitude,
}));
savedLocations.push(...newLocations);
await AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(savedLocations));
locationEventsEmitter.emit('update', savedLocations);
}
});
}
const styles = StyleSheet.create({
screen: {
flex: 1,
},
mapView: {
flex: 1,
},
buttons: {
flex: 1,
flexDirection: 'column',
justifyContent: 'space-between',
padding: 10,
position: 'absolute',
top: 0,
right: 0,
bottom: 0,
left: 0,
},
topButtons: {
flexDirection: 'row',
justifyContent: 'space-between',
},
bottomButtons: {
flexDirection: 'column',
alignItems: 'flex-end',
},
buttonsColumn: {
flexDirection: 'column',
alignItems: 'flex-start',
},
button: {
paddingVertical: 5,
paddingHorizontal: 10,
marginVertical: 5,
},
errorText: {
fontSize: 15,
color: 'rgba(0,0,0,0.7)',
margin: 20,
},
});
If you know any way to easily complete my target (of sending simple HTTP GET with location from background of Expo + RN app to my DRF backend) please let me know.
If you're using Expo you can simply use expo-task-manager and expo-location to get background location updates.
Here's a simplified version that I'm using (and it's working for sure on Android) on the App I'm currently developing:
import * as Location from 'expo-location';
import * as TaskManager from 'expo-task-manager';
import axios from 'axios';
const TASK_FETCH_LOCATION = 'TASK_FETCH_LOCATION';
// 1 define the task passing its name and a callback that will be called whenever the location changes
TaskManager.defineTask(TASK_FETCH_LOCATION, async ({ data: { locations }, error }) => {
if (error) {
console.error(error);
return;
}
const [location] = locations;
try {
const url = `https://<your-api-endpoint>`;
await axios.post(url, { location }); // you should use post instead of get to persist data on the backend
} catch (err) {
console.error(err);
}
});
// 2 start the task
Location.startLocationUpdatesAsync(TASK_FETCH_LOCATION, {
accuracy: Location.Accuracy.Highest,
distanceInterval: 1, // minimum change (in meters) betweens updates
deferredUpdatesInterval: 1000, // minimum interval (in milliseconds) between updates
// foregroundService is how you get the task to be updated as often as would be if the app was open
foregroundService: {
notificationTitle: 'Using your location',
notificationBody: 'To turn off, go back to the app and switch something off.',
},
});
// 3 when you're done, stop it
Location.hasStartedLocationUpdatesAsync(TASK_FETCH_LOCATION).then((value) => {
if (value) {
Location.stopLocationUpdatesAsync(TASK_FETCH_LOCATION);
}
});
It doesn't necessarily work with Expo, but if "eject" your project or start with the React Native CLI (via react-native init) then you could use an Android specific React Native "NativeModule" to accomplish your goal. I like using the react-native-location package, which has great support on iOS for background location updates, but on Android there is a bug currently. I put together an example project which has the necessary Android specific code inside a NativeModule you could use to start from:
https://github.com/andersryanc/ReactNative-LocationSample