我正在使用GoogleMaps API,这会返回20个附近的位置,最多可以返回60个位置。这些位置通过nextPageToken返回,它允许您获取结果的下一页(每页20个)。我尝试通过API循环,以使自己获得所有可用的位置,但有困难: func getAllNebybyLations(url:URL){通过API请求循环更新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)
}
}
接下来我们有我们与URL初始化一个getNearByLocation功能的功能。正如你所看到的,我们返回结果,将它们添加到数组中,检查是否有最大数目的结果(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。