在需要使用到需要获取用户当前位置时,获取用户定位授权需要使用CoreLocation框架提供的CLLocationManager类。在使用该类时,需要设置该类的delegate属性,将该类的实例作为delegate。然后实现CLLocationManagerDelegate协议中的方法,以获取用户定位授权状态和位置信息。
import CoreLocation
先在ViewController后面加上这个定位协议CLLocationManagerDelegate
ViewController: CLLocationManagerDelegate
并在viewDidLoad()中,创建CLLocationManager类的实例,这里使用的是获取当前3km的位置,定位精准度可以视情况改kCLLocationAccuracyKilometer,kCLLocationAccuracyNearestTenMeters等
let locationManage = CLLocationManager()//位置管理器
override func viewDidLoad() {
super.viewDidLoad()
locationManage.requestWhenInUseAuthorization()//请求授权获取当前用户位置
locationManage.delegate = self
locationManage.desiredAccuracy = kCLLocationAccuracyThreeKilometers
locationManage.requestLocation()//请求到当前位置后能够获取当前位置的所有weather信息&#x