4
【笔记】IOS 应用获取 GPS 定位
source link: https://loli.fj.cn/zh-CN/2024/01/27/IOS%E5%BA%94%E7%94%A8%E8%8E%B7%E5%8F%96GPS%E5%AE%9A%E4%BD%8D/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
IOS 应用获取 GPS 定位
import CoreLocation
实例化地址管理器对象
let locationManager = CLLocationManager()
定义委托扩展
extension ViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// 获取到GPS定位成功时执行的代码
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
// 获取到GPS定位失败时执行的代码
}
}
通过 GPS 定位获取经纬度
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)
}
}
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
}
在程序启动时申请权限
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>
配置
<?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 定位
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.requestLocation()
}
完整代码示例
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)
}
}
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK