IOS实时获取用户位置信息
2019-11-14 本文已影响0人
GIS无情老博士
做移动端GIS开发,首先就要获取用户的位置信息,今天简单叙述一下如何在IOS上获取用户的实时位置信息。
配置
- 添加请求获取位置权限的描述
在info.plist中添加键值对
- Privacy - Location Always and When In Use Usage Description 永久请求时的描述
- Privacy - Location When In Use Usage Description 临时请求的说明
-
添加在后台实时更新位置设置
允许后台位置实时更新
代码
import UIKit
import CoreLocation
class LocateViewController: UIViewController,CLLocationManagerDelegate {
let locationManager:CLLocationManager = CLLocationManager()
@IBOutlet weak var resultText: UITextView!
override func viewDidLoad() {
//使用期间获取位置
// locationManager.requestWhenInUseAuthorization()
//始终获取位置
locationManager.delegate=self
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
print("开始定位")
}
func locationManager(_ locationManager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print(locations)
let iosLocation=(locations.last?.coordinate)!
let lat=iosLocation.latitude
let lon=iosLocation.longitude
resultText.text="纬度:\(lat)\n经度:\(lon)"
}
func locationManager(_ locationManager: CLLocationManager, didFailWithError error: Error) {
print("定位失败")
print(error)
}
}