I'm attempting to access the ratings part of Google's Places API but keep coming back empty with each call attempt. Any suggestions?
func nearBy()
{
...
//starting the task to the API
let task = URLSession.shared.dataTask(with: urlRequest) { [self]
(data, response, error) in
do {
//making sure it actually has something
if let error = error {
throw error
}
guard let data = data else {
print("data is nil")
return // or throw error
}
//for debugging, show response data as text
//print(String(data: data, encoding: .utf8) ?? "?")
guard let jsonDict = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
print("response data is not a JSON object")
return // or throw error
}
//setting jsonDict to read datta from url
guard let status = jsonDict["status"] as? String, status == "OK" else {
print("API error, status is not OK")
return // or throw error
}
let token = jsonDict["next_page_token"] as? String
guard let results = jsonDict["results"] as? [[String: Any]] else {
print("`results` is not an Array of JSON object")
return // or throw error
}
for result in results{
guard let name = result["name"] as? String else {
print("value for `name` not found or not object")
return // or throw some error or ignore and continue
}
guard let geometry = result["geometry"] as? [String: Any] else {
print("value for `geometry` not found or not object")
return // or throw some error or ignore and continue
}
guard let location = geometry["location"] as? [String: Double] else {
print("value for `location` not found or not object")
return // or throw some error or ignore and continue
}
guard let lat = location["lat"],
let lng = location["lng"] else {
print("value for `lat` or `lng` not found or not number")
return // or throw some error or ignore and continue
}
guard let place = result["place_id"] as? String else {
print("value for place not found or not number")
return // or throw some error or ignore and continue
}
guard let rating= result["rating"] as? String else {
print("value for rating not found")
return // or throw some error
}
DispatchQueue.global(qos: .userInitiated).async
{
//adding to the arr the names, lat and long,
semaphore.wait()
// self.pagetoken = token ?? "EMPTY"
self.nameArray.append(name)
let coord = CLLocationCoordinate2D(latitude: lat, longitude: lng)
self.locationArray.append(coord)
self.placeArray.append(place)
//self.ratingArray.append(rating)
self.status = "Ready"
semaphore.signal()
}
}
} catch {
print(error)
let title = NSLocalizedString("There was an Error", comment: "")
let message = NSLocalizedString("We encountered an error while trying to find you a place to eat. Try again later.", comment: "")
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Okay!", style: .default))
self.present(alert, animated: true, completion: nil)
}
}
task.resume()
}