swift - 循环更新 URL 的 API 请求

标签 swift alamofire gmsplacepicker gmsplace

我正在使用 GoogleMaps API,这会返回 20 个附近位置,最多可以返回 60 个位置。返回的位置带有 nextPageToken,它允许您获取下一页结果(每页 20 个)。我试图循环访问 API 以使自己能够获取所有可用的位置,但遇到困难: func getAllNearbyLocations(url: URL) {

我正在使用 Alamofire 返回 API 请求(我也尝试过使用 URLSessions)

首先,我编写了一个函数,该函数在完成 block 中返回 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。如果其中任何一个为 false,我们将创建新的 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,并且一旦返回请求,我就想立即使用该 token 调用请求。

最佳答案

根据 Documentation ,

There is a short delay between when a next_page_token is issued, and when it will become valid. Requesting the next page before it is available will return an INVALID_REQUEST response. Retrying the request with the same next_page_token will return the next page of results.

尝试检查使用 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!)
}

关于swift - 循环更新 URL 的 API 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46558327/

相关文章:

ios - 从按钮快速删除 uitableview 中的最后一个单元格

ios - 使用 Alamofire 4 的 header 授权最佳实践,具有全局 401 代码捕获

swift - Alamofire Promise 制定通用请求方法

Swift HTTP Stub 不起作用。 (Alamofire 3.0 和 mock 鸟)

android - 如何在android中更改placepicker的语言?

ios - 在 Swift 项目中为生产禁用 NSLog

ios - 成功登录时解析切换 View Controller

android - 在 fragment 中使用 PlacePicker

swift - 打印网页第一面 View 不同