如何使用CLLocationManager-Swift获取当前经度和纬度

前端之家收集整理的这篇文章主要介绍了如何使用CLLocationManager-Swift获取当前经度和纬度前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想使用Swift获取当前的纬度和纬度,并通过标签显示.我试图这样做,但标签上没有显示.
  1. import UIKit
  2. import CoreLocation
  3. class ViewController: UIViewController,CLLocationManagerDelegate{
  4.  
  5. @IBOutlet weak var longitude: UILabel!
  6. @IBOutlet weak var latitude: UILabel!
  7. let locationManager = CLLocationManager()
  8. override func viewDidLoad() {
  9. super.viewDidLoad()
  10. if (CLLocationManager.locationServicesEnabled()) {
  11. locationManager.delegate = self
  12. locationManager.desiredAccuracy = kCLLocationAccuracyBest
  13. locationManager.requestWhenInUseAuthorization()
  14. locationManager.startUpdatingLocation()
  15. } else {
  16. println("Location services are not enabled");
  17. }
  18. }
  19. // MARK: - CoreLocation Delegate Methods
  20. func locationManager(manager: CLLocationManager!,didFailWithError error: NSError!) {
  21. locationManager.stopUpdatingLocation()
  22. removeLoadingView()
  23. if ((error) != nil) {
  24. print(error)
  25. }
  26. }
  27.  
  28. func locationManager(manager: CLLocationManager!,didUpdateLocations locations: [AnyObject]!) {
  29. var locationArray = locations as NSArray
  30. var locationObj = locationArray.lastObject as CLLocation
  31. var coord = locationObj.coordinate
  32. longitude.text = coord.longitude
  33. latitude.text = coord.latitude
  34. longitude.text = "\(coord.longitude)"
  35. latitude.text = "\(coord.latitude)"
  36. }
  37. }
IMHO,当您正在查找的解决方案非常简单时,您的代码过于复杂.

我已经通过使用以下代码

首先创建一个CLLocationManager和请求授权的实例

  1. var locManager = CLLocationManager()
  2. locManager.requestWhenInUseAuthorization()

然后检查用户是否允许授权.

  1. var currentLocation = CLLocation!
  2.  
  3. if( CLLocationManager.authorizationStatus() == CLAuthorizationStatus.AuthorizedWhenInUse ||
  4. CLLocationManager.authorizationStatus() == CLAuthorizationStatus.Authorized){
  5.  
  6. currentLocation = locManager.location
  7.  
  8. }

使用它只是这样做

  1. label1.text = "\(currentLocation.coordinate.longitude)"
  2. label2.text = "\(currentLocation.coordinate.latitude)"

您将它们设置为label.text是正确的,但我可以想到的唯一原因是用户没有给您权限,这就是为什么您的当前位置数据将为零.

但是,您需要调试并告诉我们.
另外CLLocationManagerDelegate也是没有必要的.

希望这有帮助.如果有疑问,请问

猜你在找的Swift相关文章