如何使用Swift在后台运行以提供当前位置?

要快速获取背景位置,我们需要执行几个步骤

从用户那里获取权限,在info.plist文件中添加Privacy- Location always和

使用说明时,隐私–使用说明时,并添加其各自的说明。

之后,您需要导入CoreLocation框架,这将使您能够使用所有与位置相关的库和方法。然后,您需要获得用户的许可才能使用该位置。为此,我们需要创建一个CLLocationManager对象并获得授权。

var locationManager: CLLocationManager?
override func viewDidLoad() {
   super.viewDidLoad()
   locationManager = CLLocationManager()
   locationManager?.delegate = self
   locationManager?.requestAlwaysAuthorization()
}

现在,当您运行该应用程序时,如果需要在特定模块中定位该应用程序,它将询问用户权限。之后,您可以添加以下代码以开始监视位置更改,更新位置等。

locationManager.startUpdatingLocation()
locationManager.startMonitoringSignificantLocationChanges()
locationManager.allowsBackgroundLocationUpdates = true

完成此操作后,您可以使用CLLocationManagerDelegate的didUpdateLocation方法在后台将位置更新到服务器。

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
   //点击api更新位置
}

现在,无论何时更新位置,都将调用CLLocationManagerDelegate的此方法,并且在其中可以编写代码以更新服务器上的位置。