简体   繁体   中英

Perform task (code execution/ network call) in background when user enters/exits a location region in iOS

System: In my application, I am using geofencing (monitoring a region). Whenever user enters or exits the monitored area or region, the app shows a local notification if the app is in the background or even terminated. This is working perfectly fine. The app is able to show local notificaiton.

Now I also need to submit this information (if the user is inside or outside of the monitored area) via HTTP POST call to app's backend server.

Problem: App makes API call in LocationManager's delegate methods but sometimes it works and sometimes it does not. It seems that code execution stops randomly if the app is not in foreground state.

Code sample

// MARK: - Location Manager Delegate
func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
    if region is CLCircularRegion {
        showLocalNotification(forRegion: region)// Works
        updateUserEntryAPICall(region: region) // Sometimes works
    }
}

func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {
    if region is CLCircularRegion {
        showLocalNotification(forRegion: region) // Works
        updateUserExitAPICall(region: region) // sometime works
    }
}

I did not turn on background mode capability in iOS. Still, the app is able to show local notifications. Do I need to turn it on in order to make network call to work?

在此处输入图片说明

Please help.

This looks like you're using a regular URLSession to make your API request. You need to make sure that you're doing this on a session that handles running in the background, eg by initializing it like so:

let session = URLSession(configuration: .background(withIdentifier: "foo"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM