【笔记】IOS应用获取GPS定位

前言

IOS应用获取GPS定位

引入依赖

1
import CoreLocation

实例化地址管理器对象

1
let locationManager = CLLocationManager()

定义委托

定义委托扩展

1
2
3
4
5
6
7
8
extension ViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// 获取到GPS定位成功时执行的代码
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
// 获取到GPS定位失败时执行的代码
}
}

通过GPS定位获取经纬度

1
2
3
4
5
6
7
8
9
extension ViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let lat = location.coordinate.latitude
let lon = location.coordinate.longitude
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print(error)
}
}

设置委托

1
2
3
4
5
override func viewDidLoad() {
super.viewDidLoad()

locationManager.delegate = self
}

在程序启动时申请权限

1
2
3
4
5
6
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self

locationManager.requestWhenInUseAuthorization()
}

通过info.plist配置文件设置提示内容

通过Xcode

  • 打开info.plist配置文件->+->Privacy - Location When in Use Usage Description设置弹窗内容

直接修改配置文件

  • 添加<key>NSLocationWhenInUseUsageDescription</key><string></string>配置
1
2
3
4
5
6
7
8
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSLocationWhenInUseUsageDescription</key>
<string>获取位置信息</string>
</dict>
</plist>

在程序启动时获取GPS定位

1
2
3
4
5
6
7
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()

locationManager.requestLocation()
}

完整代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import UIKit
import CoreLocation

class ViewController: UIViewController {

let locationManager = CLLocationManager()

@IBOutlet weak var label1: UILabel!
@IBOutlet weak var label2: UILabel!

override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.requestLocation()
}

}

extension ViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.last {
let lat = location.coordinate.latitude
let lon = location.coordinate.longitude
print(lat)
print(lon)
self.label1.text = String(lat)
self.label2.text = String(lon)
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print(error)
}
}

修改IOS模拟器定位

完成

参考文献

哔哩哔哩——疯狂滴小黑