如何在swift中使用CLLocationManager从当前位置获取纬度经度?

时间:2017-08-17 09:51:42

标签: swift3 cllocationmanager

我是Swift的新用户,我希望从当前位置获取latitude & longitude。使用这些latitude & longitude自动填充UITextField获取城市& Swift-3中UITextField上的国家/地区名称。提前谢谢。

1 个答案:

答案 0 :(得分:0)

请尝试以下方法:

import Foundation
import CoreLocation

class LocationViewController : UIViewController {
    @IBOutlet weak var txtField: UITextField!
    var locationManager = CLLocationManager()
    override func viewDidLoad()
    {
        super.viewDidLoad()
        self.getCurrentAddress { currentAddress, error in
            if let address = currentAddress, let city = address["City"] as? String, let country = address["Country"] as? String  {
                self.txtField.text = "\(city), \(country)"
            }
        }
    }

    func getCurrentAddress(completion: @escaping (_ currentAddress: [String:Any]?, _ error: Error?) -> ()) {
        var currentLocation: CLLocation!
        let authStatus = CLLocationManager.authorizationStatus()

        self.locationManager.requestWhenInUseAuthorization()
        if authStatus == CLAuthorizationStatus.authorizedWhenInUse || authStatus == CLAuthorizationStatus.authorizedAlways {
            currentLocation = locationManager.location
            let longi = currentLocation.coordinate.longitude
            let lat = currentLocation.coordinate.latitude
            let geoCoder = CLGeocoder()
            geoCoder.reverseGeocodeLocation(currentLocation) { placemarks, error in
                if let e = error {
                    completion(nil, e)
                } else {
                    let placeArray = placemarks
                    let placeMark = (placeArray?[0])!

                    guard let currentAddress = placeMark.addressDictionary as? [String:Any] else {
                        return
                    }
                    completion(currentAddress, nil)
                }
            }
        }
    }
}

需要在plist文件中设置NSLocationWhenInUseUsageDescription