我正在iOS中创建一个后台进程来向服务器发送位置更新,但是我无法从主应用程序控制它。大多数情况下,我在查杀服务时遇到了麻烦。我的应用程序使用一个按钮来启动/停止后台进程,并确定进程是否仍在运行。
我在一个类中使用两个方法,一个StartListening使用一个计时器来启动位置更新,而StopListening则用来杀死计时器。但我不能总是杀死后台进程,特别是如果应用程序已关闭。我没有Android的问题,因为API负责启动和停止定位过程,但iOS,我必须手动执行此操作。
public void StartListening()
{
//class setup here
if(CLLocationManager.LocationServicesEnabled)
{
locationManager.DesiredAccuracy = 10;
locationManager.StartUpdatingLocation();
taskId = UIApplication.SharedApplication.BeginBackgroundTask(() =>
{
this.timer.Dispose();
});
timer = new Timer(async (o) =>
{
CLLocation location = null;
while(location == null)
{
location = locationManager.Location;
}
if (location != null)
{
//handle location
}
}, null, TimeSpan.Zero, TimeSpan.FromSeconds(UpdateInterval));
UIApplication.SharedApplication.EndBackgroundTask(taskId);
}
}
public void StopListening()
{
this.locationManager.StopUpdatingLocation();
if(taskId != 0)
{
if (this.timer != null)
{
this.timer.Change(Timeout.Infinite, Timeout.Infinite);
this.timer.Dispose();
}
}
}
我期待StopLocation停止后台进程,并且在测试中,它工作正常,但是当我实际尝试使用该应用程序一段时间时,它似乎“忘记”关于后台进程而不是正确杀死它。有没有人建议为什么这是/如何解决这个问题?任何帮助表示赞赏。
添加以下代码
if(CLLocationManager.LocationServicesEnabled)
{
locationManager.DesiredAccuracy = 10;
locationManager.RequestWhenInUseAuthorization();
locationManager.AllowsBackgroundLocationUpdates = false;
locationManager.StartUpdatingLocation();
//...
}
RequestWhenInUseAuthorization仅在前台操作模式切换到后台操作模式时有效。例如,如果App切换到后台操作模式,则代理方法didUpdateLocations
将不会继续。
不要忘记在info.plist中添加隐私
<key>NSLocationWhenInUseUsageDescription</key>
<string>xxxx</string>