[英]Loop over an API request updating the URL
我正在使用GoogleMaps API,它會返回附近的20個位置,並且最多可以返回60個位置。 這些位置將通過nextPageToken返回,您可以通過它獲取下一頁結果(每頁20個)。 我試圖遍歷API,以使自己能夠獲得所有可用位置,但遇到困難:func getAllNearbyLocations(url:URL){
我正在使用Alamofire返回API請求(我也嘗試過使用URLSessions)
首先,我把一個函數返回到完成塊中的json字典中
// This function returns the JSON from a specific URL
func getJsonFromURL(url: URL, completionHandler: @escaping (NSDictionary) -> ()) {
Alamofire.request(url).responseJSON { response in
let json = response.result.value as! NSDictionary
completionHandler(json)
}
}
接下來,我們有一個getNearByLocation函數,我們使用一個URL對其進行初始化。 如您所見,我們返回結果,將它們添加到數組中,檢查是否有最大數量的結果(60)或不再有nextPageToken。 如果其中任何一個為假,我們將創建新的URL並再次觸發我們當前使用的函數。 當我們返回所有新位置時,循環結束。
func getAllNearbyLocations(url: URL) {
self.getJsonFromURL(url: url) { (dictionary) in
let newLocations: NSArray = dictionary.value(forKey: "results") as! NSArray
self.locations.addObjects(from: newLocations as! [Any])
if self.locations.count >= 60 {
self.sendNewLocations(locations: self.locations)
}
else {
// We want to now update the URL we are using and search again
if let newPageToken = dictionary["next_page_token"] {
let newURL = self.rootSearchURL + "&pagetoken=" + (newPageToken as! String)
let url = URL(string: newURL)
// We want to get our current URL and remove the last characters from it
self.getAllNearbyLocations(url: url!)
}
else {
// If we have no more pages then we return what we have
self.sendNewLocations(locations: self.locations)
}
}
}
}
奇怪的是,當我使用斷點測試代碼時,它會按預期返回。 它遍歷該函數,添加所有新位置並返回。 當我實時運行它時,返回的字典無法正確返回(不包含位置或下一頁標記),因此我的函數僅返回前20個位置。
我之前使用過API請求,但從未如此連續地使用過。 我覺得這是一個陷阱22,因為在調用請求之前我不知道新的pageToken,並且一旦返回請求,我想立即使用該令牌調用請求。
根據文檔 ,
從發出next_page_token到它生效之間有短暫的延遲。 在下一頁可用之前請求它會返回一個INVALID_REQUEST響應。 使用相同的next_page_token重試請求將返回下一頁結果。
嘗試檢查使用new_page_token
檢索數據時得到的結果
嘗試這樣打電話:
let newURL = self.rootSearchURL + "&pagetoken=" + (newPageToken as! String)
let url = URL(string: newURL)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3) {
// We want to get our current URL and remove the last characters from it
self.getAllNearbyLocations(url: url!)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.