Элемент URLQuery не получает координату местоположения

Мне интересно, что может быть причиной моей проблемы. Я использую основное местоположение, чтобы получить местоположение моих координат, которое я использую в сетевом методе как URLQueryItem, чтобы получить ответ от API. Но вывод консоли показывает, что запрос широты и запрос долготы равны 0, в то время как у меня есть значение широты и долготы. Я использую сетевой метод внутри моего viewdidload.

Спасибо за все ответы и пояснения.

  var queryLattitudeItem : Double = 0
  var queryLongitudeItem : Double = 0

func network () {

        let configuration = URLSessionConfiguration.default
        configuration.waitsForConnectivity = true
        let session = URLSession(configuration: configuration)
        guard let urls = URL(string:"https://api.yelp.com/v3/businesses/search") else { return }
        var urlcomponent = URLComponents(string: "\(urls)")
        let queryLat = URLQueryItem(name:"latitude" , value: "\(queryLattitudeItem)")
        let queryLong = URLQueryItem(name: "longitude", value: "\(queryLongitudeItem)")
        let queryItemterm = URLQueryItem(name: "term", value: "restaurant")
        let queryLimit = URLQueryItem(name: "limit", value: "10")
        urlcomponent?.queryItems = [queryItemterm,queryLat,queryLong,queryLimit]
        print(urlcomponent!)
        print(queryLat)
        print(queryLong)
        var request = URLRequest(url: urlcomponent!.url!)
        request.httpMethod = "GET"
        request.addValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")

        let task = session.dataTask(with: request) { (data, response, error) in

            if let response = response as? HTTPURLResponse {
                print(response)

            } else{
                print("error")
            }
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let location = locations[locations.count - 1]

        if location.horizontalAccuracy > 0 {
            locationManager.stopUpdatingLocation()
          print("\(location.coordinate.longitude), \(location.coordinate.latitude)")

        }
        let latitude : Double = (location.coordinate.latitude)
        let longitude : Double = location.coordinate.longitude
        print("This is lat: \(latitude), et long\(longitude)")
        queryLattitudeItem = latitude
        queryLongitudeItem = longitude


    }

Консольный вывод

https://api.yelp.com/v3/businesses/search?term=restaurant&latitude=0.0&longitude=0.0&limit=10
latitude=0.0
longitude=0.0
-73.984638, 40.759211
This is lat: 40.759211, et long-73.984638
<NSHTTPURLResponse: 0x600003a91ec0> { URL: https://api.yelp.com/v3/businesses/search?term=restaurant&latitude=0.0&longitude=0.0&limit=10 } { Status Code: 200, Headers {
    "Accept-Ranges" =     (

person Vangola    schedule 23.07.2019    source источник
comment
Попробуйте сделать сетевой вызов из вашего метода didUpdateLocations после того, как вы установили queryLattitudeItem и queryLongitudeItem. Прямо сейчас вы делаете сетевой вызов до того, как был вызван метод делегата locationManager.   -  person Don    schedule 23.07.2019
comment
Вы правы, это работает. Черт, мне плохо. Я даже не думал об этом. Я пытался добавить сетевой метод в другое представление, чтобы понять. Спасибо   -  person Vangola    schedule 23.07.2019
comment
Да, вызов делегата locationManager является асинхронным, поскольку устройству может потребоваться некоторое время, чтобы получить точное местоположение. Рад, что у тебя получилось.   -  person Don    schedule 23.07.2019


Ответы (1)


Одна стилистическая вещь, которую я бы сделал с вашим кодом, - это использовать какую-то структуру для хранения строк, чтобы они не засорялись в вашем коде. Когда что-то выходит из строя, вы можете пойти в одно место, чтобы отладить это, а не копаться в куче кода. Здесь я сохраняю строку в перечислении как статический let (потому что я ненавижу rawValues):

enum Endpoint {
    static let yelp = "https://api.yelp.com/v3/businesses/search"
}

Затем я бы отказался от объявлений var для широты и долготы:

var queryLattitudeItem : Double = 0 // ???? nuke
var queryLongitudeItem : Double = 0 // ???? nuke

Вместо этого я бы обновил ваш метод сетевого запроса, чтобы он принимал CLLocationCoordinate2D прямо из метода делегата, например:

func getYelpInfo(for coordinate: CLLocationCoordinate2D) {

    // omitted your networking code...this is just the URL creation code

    var components = URLComponents(string: Endpoint.yelp)
    let queryLat = URLQueryItem(name: "latitude", value: String(coordinate.latitude))
    let queryLong = URLQueryItem(name: "longitude", value: String(coordinate.latitude))
    let queryLimit = URLQueryItem(name: "limit", value: "10")
    components?.queryItems = [queryLat, queryLong, queryLimit]

    // You could use a guard statement here if you want to exit out, too
    if let url = components?.url {
        var request = URLRequest(url: url)
        // do your networking request
    }


    print(components!.url!.absoluteString)
}

Затем в вашем didUpdateLocations я бы вызвал обновленный метод, например:

getYelpInfo(for: location.coordinate)

Ваш обновленный метод выглядит так:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let location = locations[locations.count - 1]

    if location.horizontalAccuracy > 0 {
        locationManager.stopUpdatingLocation()
        getYelpInfo(for: location.coordinate)
        print("\(location.coordinate.longitude), \(location.coordinate.latitude)")

    }
}
person Adrian    schedule 23.07.2019