Элемент 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" = (
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)")
}
}