Hi everyone,
I've implemented geofencing in my app, and it works well when the device is connected to the internet. The app successfully triggers region entry and exit events, even when it's in a terminated state, and sends the details to the server.
However, I'm facing an issue with offline functionality. I attempted to cache geofence events (region entry/exit) when the device is offline and send them to the server once the device comes back online. I’ve tried using both UserDefaults and Core Data for caching these events, but the offline events are not being stored or processed correctly.
Here’s the code that triggers the region events:
func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
if let region = region as? CLCircularRegion {
handleRegionEvent(region: region, eventType: "enter")
}
}
func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
if let region = region as? CLCircularRegion {
handleRegionEvent(region: region, eventType: "exit")
}
}
The region entry/exit triggers correctly, and I even receive notifications. However, nothing is being saved to storage.
To cache events, I'm using this method:
private func cacheEvent(_ event: GeofenceEvent) {
var cachedEvents = getCachedEvents()
cachedEvents.append(event)
if let encoded = try? JSONEncoder().encode(cachedEvents) {
UserDefaults.standard.set(encoded, forKey: cachedEventsKey)
}
}
For UserDefaults, we've added the app group and suite name, but it's still not working as expected.
Has anyone encountered similar issues or have any suggestions on how to reliably cache and sync geofence events during offline scenarios?
Any help would be greatly appreciated!