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


要在 Swift 中获取后台位置,我们需要执行以下几个步骤

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

When in usage Description,Privacy - When in usage description 并添加各自的描述。

之后,你需要导入 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]) {
   // Hit api to update location
}

现在,每当位置更新时,都会调用 CLLocationManagerDelegate 的此方法,我们可以在其中编写将位置更新到服务器的代码。

更新于:2019年7月30日

663 次浏览

启动你的 职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.