我正在使用Google Places API在一个表格视图中输出餐馆的名称。我已经能够解析JSON并获得这些地方的名称和图片。但是,表格视图只包含20个结果。因此,我发现我需要使用提供的next_page_token来获得其余数据。但是,当我获得next_page_token并将其放入请求URL中时,来自第一查询的数据在表格视图内重复多次。
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
var location : CLLocation? = locations.last
var searchURL = NSString(format: "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=50.940463,-114.077553&radius=50000&type=restaurant&key=MY_API_KEY") as? String
callAlamo(url: searchURL!)
}
func callAlamo(url:String){
Alamofire.request(url).responseJSON(completionHandler: { response in
self.parseData(JSONData: response.data!)
})
}
// PARSING JSON DATA FOR GETTING NAME AND PICTURE OF PLACES AND GETTING LATITUDE AND LONGITUDE
func parseData(JSONData:Data){
do{
var myReadableJSON = try JSONSerialization.jsonObject(with: JSONData, options: .mutableContainers) as! JSONStandard
// PARSING THROUGH JSON DATA TO GET NAMES AND PICTURES OF PLACES, THEN PUTTING
// THEM INTO AN ARRAY AND OUTPUTTING THEM ONTO TABLE VIEW CELL
if let results = myReadableJSON["results"] as? [JSONStandard]{
for i in 0..<results.count{
let item = results[i]
print("Item is: ",item)
let names = item["name"] as! String
placeNames.append(names)
// GETTING PHOTO URL WITH photo_reference AND PUTTING THEM INTO imageURL ARRAY
if let photos = item["photos"] as? [JSONStandard]{
for k in 0..<photos.count{
let photo = photos[k] as JSONStandard
let photoRef = photo["photo_reference"] as! String
let photoURL = NSString(format: "https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=%@&key=MY_API_KEY", photoRef) as? String
imageURL.append(photoURL!)
}
}
if let geometry = item["geometry"] as? JSONStandard{
if let location = geometry["location"] as? [String : Any]{
let latitude = location["lat"] as? Double
let longitude = location["lng"] as? Double
}
}
}
// CHECK TO SEE IF JSON DATA CONTAINS next_page_token. IF IT DOES, REPEAT PROCESS OF
// PARSING THROUGH JSON DATA AND GET SECOND PAGE OF DATA. REPEAT UNTIL LAST PAGE
// DOESN'T CONTAIN next_page_token.
if (myReadableJSON["next_page_token"] != nil){
nextPageToken = myReadableJSON["next_page_token"] as! String
let nextPageGoogleURL = NSString(format:"https://maps.googleapis.com/maps/api/place/nearbysearch/json?pagetoken=%@&key=MY_API_KEY",nextPageToken ) as String
DispatchQueue.main.async {
self.callAlamo(url: nextPageGoogleURL)
}
}
// SHOULD BE PLACED AT THE END OF GATHERING DATA
locationManager.stopUpdatingLocation()
self.tableView.reloadData()
imageURL.removeAll()
placeNames.removeAll()
}
}
catch{
print(error)
}
}
- 更新日期:**
我能够找到解决我问题的方法。多亏了stack overflow上的另一个线程。
我只需要在parseData()函数中添加一个if let条件,但要将其置于循环之外,并添加一个定时器延迟,正如在所提供的SO查询的答案中提到的,从发出next_page_token到您可以访问该数据之间存在一个时间延迟,因此我添加了一个轻微的时间延迟。
func parseData(JSONData:Data){
do{
var readableJSON = try JSONSerialization.jsonObject(with: JSONData, options: .mutableContainers) as! JSONStandard
placeNames.removeAll()
if let results = readableJSON["results"] as? [JSONStandard]{
print("JSON: ",results)
for i in 0..<results.count{
let item = results[i]
let names = item["name"] as! String
placeNames.append(names)
if let geometry = item["geometry"] as? JSONStandard{
if let location = geometry["location"] as? [String : Any]{
self.latitude = (location["lat"] as? Double)!
self.longitude = (location["lng"] as? Double)!
}
}
let marker = GMSMarker(position: CLLocationCoordinate2D(latitude: latitude, longitude: longitude))
marker.icon = UIImage(named: "locationMarker")
print(placeNames[i],"\n")
marker.title = placeNames[i]
marker.snippet = "Nothing"
marker.map = self.googleMapsContrainer
}
}
if let pageToken = readableJSON["next_page_token"]{
let newURL = NSString(format:"https://maps.googleapis.com/maps/api/place/nearbysearch/json?pagetoken=\(pageToken)&key=MY_API_KEY" as NSString) as? String
let when = DispatchTime.now() + 2
DispatchQueue.main.asyncAfter(deadline: when, execute: {
self.callAlamo(url: newURL!)
})
}
}
catch{
print(error)
}
}`
2条答案
按热度按时间alen0pnh1#
理想情况下,google最多返回20个位置的结果(每次搜索最多可以返回60个结果),如果搜索包含20个以上的结果,那么你将在你的响应对象中得到*next_page_token***,如果next_page_token为nil或没有返回,那么没有进一步的结果。**
样本响应对象
分页请求的示例url应该包含pagetoken作为参数https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=500&type=restaurant&keyword=cruise&key=YOUR_API_KEY&pagetoken=Xyz
参考Google places Api
fdx2calv2#
对于其他可能发现这个问题的人,在我的例子中,我犯了一个错误,即发送
next_page_token=
作为url参数,但是正确的发送参数是pagetoken=