我使用Google Places API在表格視圖中輸出餐館名稱。我已經能夠解析JSON並獲取地點的名稱和圖片。但是,表格視圖僅包含20個結果。所以我發現我需要使用提供的next_page_token來獲取其餘的數據。但是,當我得到next_page_token並將其放入請求URL中時,第一個查詢中的數據會在表視圖中重複多次。 'Google Places API - 下一頁令牌返回相同的結果
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)
}
}
UPDATE:
我能解決找出我的問題。感謝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)
}
}`
感謝您的評論。您是否說我創建的請求URL是不正確的格式?因爲,我把網址放到網頁瀏覽器中,我可以得到剩下的結果。 – notSoExperiencedCoder
我的意思是說,您的搜索結果不包含超過20個結果,因此在響應中沒有next_page _令牌,請嘗試新的座標或關鍵字,如果您仍未獲得理想的結果,請給我座標或關鍵字您正在搜索 –
請查看我的更新代碼。謝謝 – notSoExperiencedCoder