【发布时间】:2019-04-08 07:11:21
【问题描述】:
您好,我只需要一些帮助来检索用户位置的纬度和经度,并能够将其显示在 UILabel 上。 我对 swift 很陌生,而且我知道如何接收这些值,因为我使用过 void 函数,但实际显示它们是让我感到兴奋的原因
谢谢
【问题讨论】:
标签: swift geolocation uilabel
您好,我只需要一些帮助来检索用户位置的纬度和经度,并能够将其显示在 UILabel 上。 我对 swift 很陌生,而且我知道如何接收这些值,因为我使用过 void 函数,但实际显示它们是让我感到兴奋的原因
谢谢
【问题讨论】:
标签: swift geolocation uilabel
要收集位置变化数据,您需要在 Info.plist 文件中设置两个特殊字符串
然后执行此操作
import CoreLocation
final class ViewController: UIViewController {
@IBOutlet weak var coordinatesLabel: UILabel!
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.requestAlwaysAuthorization()
locationManager.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
locationManager.startUpdatingLocation()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
locationManager.stopUpdatingLocation()
}
}
extension ViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
guard status == .authorizedAlways || status == .authorizedWhenInUse else {
// Handle when no access
return
}
manager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.first?.coordinate else { return }
coordinatesLabel.text = "Lat: \(location.latitude), Lng: \(location.longitude)"
}
}
【讨论】: