获取用户位置
程序员文章站
2024-02-20 15:41:22
...
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate{
var locationManager = CLLocationManager()
@IBOutlet weak var latitudeLabel: UITextField!
@IBOutlet weak var longitudeLabel: UITextField!
@IBOutlet weak var locationErrorLable: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self as CLLocationManagerDelegate
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
locationErrorLable.isHidden = true
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
locationErrorLable.isHidden = true
let location = locations.last!
let latitude = location.coordinate.latitude
let longitude = location.coordinate.longitude
latitudeLabel.text = String(format: "Latitude: %.4f", latitude)
longitudeLabel.text = String(format: "longitude: %.4f", longitude)
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
locationErrorLable.isHidden = false
locationErrorLable.text = (error as! String)
}
}