位置经理包装

位置管理器是一种包装器,可以以更简单的方式使用CLLocationManager(iOS框架使用GPS)并摆脱所有这些委托和错误处理。 位置管理器同时提供了一次性定位和实时跟踪的功能。

特征:

  • 易于使用。
  • 提供事先的错误处理。
  • 根据设备电池百分比调整位置精度。

如何使用:

  • 不要忘记添加“ NSLocationWhenInUseUsageDescription”键和“ NSLocationAlwaysAndWhenInUseUsageDescription”键到您的Info.plist文件中。 (Xcode在Info.plist编辑器中将这些键显示为“隐私-使用时位置用法说明”和“隐私-始终和使用时位置用法说明”。)
  • 1.一次获取位置信息:
let locationManager = LocationManager(withAccuracy: LMLocationAccuracy.bestForNavigation) 
locationManager.getCurrentLocation { (response) in
switch response {
case .failure(let locationError):
switch locationError {
case .authorizationFailed(let description):
print(description)
case .locationUpdationFailed(let description):
print(description)
}
case .success(let location):
print("location is :", location)
self.lbllat.text = "\(location.coordinate.latitude)"
self.lblLong.text = "\(location.coordinate.longitude)"
}
}
  • 2.对于实时跟踪:
 let locationManager = LocationManager(withAccuracy: LMLocationAccuracy.bestForNavigation) 
 locationManager.startLiveTracking { (response) -> Bool in 
switch response {
case .failure(let locationError):
switch locationError {
case .authorizationFailed(let description):
print(description)
case .locationUpdationFailed(let description):
print(description)
}
case .success(let location):
print("location is :", location)
self.lbllat.text = "\(location.coordinate.latitude)"
self.lblLong.text = "\(location.coordinate.longitude)"
}
return true
}
  • **实时跟踪关闭中返回的布尔值确保了何时停止更新位置,当您要停止位置更新时返回false,返回true以继续更新位置。

Github链接:https://github.com/akashbhardwaj/LocationManagerWrapper

谢谢