Search code examples
androidiosgeolocationreact-native

Is it possible without react-native to gather geolocation information in a background task for Android and/or iOS?


Is it possible in react-native to execute a background task with monitoring GPS position (without running the whole app in the background), even if the phone is locked? I want to show some information (notification) onscreen when the phone will be in some position.

I need to declare the subject of a project in my studies, but I don't know if it's possible to implement this functionality.


Solution

  • It most certainly is... if you have only one given position (Or fewer than 20 positions) what you'd be best using is CoreLocation's geofencing APIs!

    You can set up a region like so:

    if CLLocationManager.isMonitoringAvailable(for: CLCircularRegion.self) {
        // Register the region.
        let region = CLCircularRegion(
            center: center, 
            radius: maxDistance, identifier: identifier
        )
        region.notifyOnEntry = true
    
        locationManager.startMonitoring(for: region)
    }
    

    (Assuming you have already requested and checked the user's location permissions)!

    Your app will then get launched in the background whenever a region monitoring event occurs, so you must make sure to setup a new CLLocationManager and give it a delegate to receive the updates in your application(_application:didFinishLaunchingWithOptions) function!

    You can then use the delegate callbacks to trigger a local notification.

    There is a slight caveat here, that this won't work if the user has disabled background app refresh for your app!

    Luck, there's already a react-native library that allows you to setup these regions: https://github.com/martijndeh/react-native-region-monitor. Unfortunately I do think it will launch your JavaScript app fully (in the background of course) when a notification comes through, but that's not too big an issue.

    There may also be info on the GitHub provided for how to implement this on Android too!