【问题标题】:Pass longitude and latitude from CLLocationManager to URL?将经度和纬度从 CLLocationManager 传递到 URL?
【发布时间】:2017-06-06 23:56:40
【问题描述】:

我试图将我的纬度和经度传递给我的 url 参数,但返回 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)

}

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

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

谢谢

【问题讨论】:

  • 你到底在哪里声明latlong?你在哪里试图得到他们的价值观?您是否将委托分配给 CLLocationManager 实例?
  • 在我的课之后,我确实在视图上分配了它的委托

标签: ios swift cllocationmanager


【解决方案1】:

尝试类似:

斯威夫特 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....
}

【讨论】:

  • 我试过了,但是没有用,由于某种原因,值没有从委托中出来,如果我在委托之外打印 lat,它会返回 nil
  • 搞定了,非常感谢您的帮助,非常感谢您的帮助
【解决方案2】:

我认为 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"

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

斯威夫特 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.
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    相关资源
    最近更新 更多