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

时间:2017-06-06 23:56:40

标签: ios swift cllocationmanager

我试图将我的纬度和经度传递给我的网址参数但是返回Nil,但是当我在代表中打印时,它返回经度和纬度,我似乎无法找到问题,我尝试了很多不同的方法,似乎没有任何工作

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

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)

}

这里将它们传递给我在我的网址参数中使用的变量,但它们返回nil并且我不明白为什么

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

谢谢

2 个答案:

答案 0 :(得分:1)

尝试类似:

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....
}

答案 1 :(得分:0)

我认为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.
    }