【发布时间】:2018-03-07 23:44:35
【问题描述】:
您好,我正在制作一个向 Web 应用程序发送 POST 位置更新请求的应用程序。我有一个名为 locationUpdate 的函数,一旦应用程序处于后台,我想间歇性地调用它,但是我还没有找到方法。
我已经设置了“始终允许位置”等所有基本功能。由于 AppDelegate 文件中的代码,该应用当前在进入后台时会立即发出一个 HTTP POST 请求:
func applicationDidEnterBackground(_ application: UIApplication) {
sendLocation.determineCurrentLocation()
}
我在 AppDelegate 中也有这个,因为我在一些堆栈溢出答案中看到了它:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum)
return true
}
因此,除了应用程序不会多次调用 sendLocation.determineCurrentLocation()(发出 POST 请求的函数)之外,这一切都是在应用程序关闭时。
谁能告诉我如何实现 sendLocation 函数的间歇调用?
已编辑以显示我的 locationManager:
func determineCurrentLocation(){
locationManager.delegate = self
locationManager.allowsBackgroundLocationUpdates=true
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
if CLLocationManager.locationServicesEnabled(){
DispatchQueue.main.async {
self.locationManager.requestLocation()
}
}
else if (!CLLocationManager.locationServicesEnabled())
{
print("You need to enable location services to use this app")
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]){
locationManager.stopUpdatingLocation()
userLocation = locations[0] as CLLocation
locationStruct.latitude=userLocation?.coordinate.latitude
locationStruct.longitude=userLocation?.coordinate.longitude
print(userLocation?.coordinate.latitude)
print(userLocation?.coordinate.longitude)
sendLocationPost()
}
【问题讨论】:
-
你需要在
didUpdateLocations发帖 -
@Paulw11 你能详细说明你的意思吗?当我调用 sendLocation.determineCurrentLocation() 时,该函数调用 didUpdateLocations()
-
您需要获得后台位置权限,开启重要的位置更新并致电
startUpdatingLocation,并在您的位置管理器上启用后台更新。然后,您将在后台收到对didUpdateLocations的呼叫。您需要仔细考虑您要求的准确度,因为频繁的高精度位置更新会显着影响电池寿命。 -
@Paulw11 我编辑了我的答案以包括我的位置经理,因为我认为我已经完成了你提到的所有事情,但它仍然不起作用。你是说在我的 AppDelegates 当前状态下它应该定期更新吗?因为除非我向 AppDelegate 本身添加一些东西,否则我无法看到它会如何做到这一点。
-
您需要致电
startUpdatingLocation而不是requestLocation-requestLocation只提供一次性更新。startUpdatingLocation会持续更新。您可能希望在didUpdateLocations中添加一些代码,以便每隔几分钟更新一次服务器,因为如果用户移动,您的设置将每秒提供一次位置更新