-
-
Save rodrigoespinozadev/1a6b4e41502e3e2c10c70d6fc1d8177b to your computer and use it in GitHub Desktop.
background location config
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Permissions, Location, TaskManager, Notifications } from 'expo' | |
import axios from 'axios' | |
export const BACKGROUND_LOCATION_UPDATES_TASK = 'background-location-updates' | |
export const BACKGROUND_GEOFENCING_UPDATES_TASK = 'background-geofencing-updates' | |
const geofences = [] //I get this from the server, omitted for sake of clarity | |
const url = 'api.metoo.io' | |
TaskManager.defineTask(BACKGROUND_LOCATION_UPDATES_TASK, handleLocationUpdate) | |
TaskManager.defineTask(BACKGROUND_GEOFENCING_UPDATES_TASK, handleGeofencingUpdate) | |
export async function initializeBackgroundLocationTasks(){ | |
try { | |
await Permissions.askAsync(Permissions.LOCATION) | |
let isBGLRegistered = await TaskManager.isTaskRegisteredAsync(BACKGROUND_LOCATION_UPDATES_TASK) | |
if (!isBGLRegistered) await Location.startLocationUpdatesAsync(BACKGROUND_LOCATION_UPDATES_TASK, { | |
accuracy: Location.Accuracy.High, timeInterval: 5000, distanceInterval: 10, | |
}) | |
let isGeofencingRegistered = await TaskManager.isTaskRegisteredAsync(BACKGROUND_GEOFENCING_UPDATES_TASK) | |
if (!isGeofencingRegistered) await Location.startGeofencingAsync(BACKGROUND_GEOFENCING_UPDATES_TASK, geofences) | |
return true | |
} catch (error) { | |
return false | |
} | |
} | |
export async function handleLocationUpdate({ data, error }) { | |
if (error) return | |
const username = await AsyncStorage.getItem('username') | |
if (data) { | |
try { | |
const { locations } = data | |
const res = await axios.get(`${url}/${__DEV__ ? 'dev/' : ''}userlocation/${username}/${JSON.stringify(locations[0].coords)}`) | |
} catch (error) { | |
console.log('location update error',error) | |
} | |
} | |
} | |
export async function handleGeofencingUpdate({ data: { eventType, region }, error }) { | |
if (error) return | |
const username = await AsyncStorage.getItem('username') | |
const url = eventType == Location.GeofencingEventType.Enter ? 'entered' : 'exited' | |
try { | |
// const response = await metooApi.sendLocation({ link: JSON.stringify(region), token }) | |
const response = await axios.get(siccurl(`${url}/${__DEV__ ? 'dev/' : ''}geofence/${username}/${url}/${JSON.stringify(region)}`)) | |
const body = eventType === Location.GeofencingEventType.Enter ? 'Entered region' : 'Exited region' | |
Notifications.presentLocalNotificationAsync({ title: '', body, ios: { sound: true } }) | |
} catch (error) { | |
console.log('geofence error',error) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment