小编典典

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

swift

我想使用Swift获取位置的当前经度和纬度,并通过标签显示它们。我尝试执行此操作,但标签上没有任何显示。

import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate{

    @IBOutlet weak var longitude: UILabel!
    @IBOutlet weak var latitude: UILabel!
    let locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()
        if (CLLocationManager.locationServicesEnabled()) {
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.requestWhenInUseAuthorization()
            locationManager.startUpdatingLocation()
        } else {
            println("Location services are not enabled");
        }
    }

    // MARK: - CoreLocation Delegate Methods

    func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
         locationManager.stopUpdatingLocation()
         removeLoadingView()
         if (error) != nil {
             print(error)
          }
     }

    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
        var locationArray = locations as NSArray
        var locationObj = locationArray.lastObject as CLLocation
        var coord = locationObj.coordinate
        longitude.text = coord.longitude
        latitude.text = coord.latitude
        longitude.text = "\(coord.longitude)"
        latitude.text = "\(coord.latitude)"
    }
}

阅读 641

收藏
2020-07-07

共1个答案

小编典典

恕我直言,当您寻找的解决方案非常简单时,您就使代码复杂化了。

我已经通过使用以下代码来做到这一点:

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

var locManager = CLLocationManager()
locManager.requestWhenInUseAuthorization()

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

var currentLocation: CLLocation!

if 
   CLLocationManager.authorizationStatus() == .authorizedWhenInUse ||
   CLLocationManager.authorizationStatus() ==  .authorizedAlways
{         
    currentLocation = locManager.location        
}

用它来做到这一点

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

您将它们设置为的想法label.text是正确的,但是我能想到的唯一原因是用户未给予您许可,这就是为什么您当前的位置数据将为零。

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

希望这会有所帮助。询问是否有疑问。

2020-07-07