[英]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. 现在,我还需要通过HTTP POST调用向应用程序的后端服务器提交此信息(如果用户位于受监视区域之内或之外)。
Problem: App makes API call in LocationManager's delegate methods but sometimes it works and sometimes it does not. 问题: App在LocationManager的委托方法中进行API调用,但有时可以,有时却不起作用。 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. 我没有在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. 看起来您正在使用常规
URLSession
发出API请求。 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"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.