1

I am wondering what can the be reason of my issue. I am using core location in order to get the my coordinates location, which I use in the network method as a URLQueryItem in order to get a response from the API. But the console output shows that the latitude query and longitude query are both equal to 0 while I have my a latitude and longitude value. I use the network method inside my viewdidload.

Thanks for all responses and explanations.

  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


    }

Console output

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" =     (
Vangola
  • 116
  • 7
  • Try making the network call from your didUpdateLocations method after you've set the queryLattitudeItem and queryLongitudeItem. Right now, you're making the network call before the locationManager delegate method has been called. – Don Jul 23 '19 at 02:17
  • You are right, it’s working. Damn I feel bad. I did not even think about. I was trying to add the network method in different view in order to understand. Thanks – Vangola Jul 23 '19 at 02:26
  • Yeah, the locationManager delegate call is asynchronous as it could take the device awhile to get an accurate location. Glad you got it working. – Don Jul 23 '19 at 02:28

1 Answers1

0

One stylistic thing I'd do with your code is utilize some sort of structure for storing strings so they're not littered throughout your code. When something fouls up, you can go to one spot to debug it rather than plowing through a bunch of code. Here, I store the string in an enum as a static let (b/c I hate rawValues):

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

Next, I'd ditch the var declarations for latitude and longitude:

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

Instead, I'd update your network request method to accept a CLLocationCoordinate2D straight from the delegate method, like so:

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

Next, in your didUpdateLocations, I'd call the updated method, like so:

getYelpInfo(for: location.coordinate)

Your updated method looks like this:

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)")

    }
}
Adrian
  • 14,925
  • 16
  • 92
  • 163