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

标签 ios swift location core-location cllocationmanager

我想使用 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)"
    }
}

最佳答案

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

我是用下面的代码完成的:

首先创建一个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 也不是必需的。

希望这对您有所帮助。如果您有疑问,请提出。

关于ios - 如何使用CLLocationManager-Swift获取当前经纬度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26741591/

相关文章:

javascript - 用户提交位置后重新居中 Google map

ios - 持续后台更新位置

ios - iPhone - 在 UITableView 中选择编辑按钮时添加 "Add"按钮

ios - 如何检查 NSDate 是否在特定月份?

ios - 如何在新的 UIViewController 中打开我在 UIWebView 中的 mp3 链接?

ios - 如何子类化 UICollectionViewFlowLayout 以便可以覆盖 layoutAttributesForElementsInRect

ios - Swift 以编程方式删除标签栏

iPhone - 后台轮询事件

ios - didReceiveRemoteNotification 和 didFinishLaunchingWithOptions 的果酱 Hook

ios - 在 Swift 中使用 UIAlertViewController 时无法从 shouldPerformSegue 返回控制