将经度和纬度从 CLLocationManager 传递到 URL?

Pass longitude and latitude from CLLocationManager to URL?

我正在尝试将我的纬度和经度传递给我的 url 参数但是 return 为 Nil,但是当我在委托中打印时它 return 是经度和latitude 和我似乎找不到问题,我尝试了很多不同的方法,但似乎没有任何效果

这是我存储纬度和经度的变量

var lat: Double! var long: Double!

这是我的代表

func locationManager(_ manager:CLLocationManager, didUpdateLocations locations: [CLLocation]){

    currentLocation = manager.location!.coordinate

    let locValue:CLLocationCoordinate2D = currentLocation!

    self.long = locValue.longitude
    self.lat = locValue.latitude

    print(lat)
    print(long)

}

然后将它们传递给我在 URL 参数中使用的变量,但它们 return 为零,我不明白为什么

let userLat = String(describing: lat)
let userLong = String(describing: long)

谢谢

试试这样的:

Swift 3

func locationManager(_ manager:CLLocationManager, didUpdateLocations locations: [CLLocation]){

    if let last = locations.last {
        sendLocation(last.coordinate)
    }

}

func sendLocation(_ coordinate: CLLocationCoordinate2D) {
    let userLat = NSString(format: "%f", coordinate.latitude) as String
    let userLong = NSString(format: "%f", coordinate.longitude) as String

    // Run API Call....
}

我认为Joseph K 的回答不正确。它四舍五入了纬度和经度的值。它将类似于下面的代码。

let coordinate = CLLocationCoordinate2D(latitude: CLLocationDegrees(exactly: 35.6535425)!, longitude: CLLocationDegrees(exactly: 139.7047917)!)

let latitude = coordinate.latitude // 35.6535425
let longitude = coordinate.longitude // 139.7047917

let latitudeString = NSString(format: "%f", latitude) as String // "35.653543"
let longitudeString = NSString(format: "%f", longitude) as String // "139.704792"

所以正确且简单的代码是:

Swift 3

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        guard let coordinate = locations.last?.coordinate else { return }

        let latitude = "\(coordinate.latitude)"
        let longitude = "\(coordinate.longitude)"

        // Do whatever you want to make a URL.
    }