Google 放置 Web 服务:如何在 Swift 3 中获取下一页结果



我正在我的iOS应用程序中使用Google Web Service API来查找用户位置附近的临终关怀位置。 我可以获取结果的第一页,但使用pagetoken检索下一页结果失败。 下面是我的搜索功能。 任何关于我出错的地方的帮助(以前从未使用过URLSession(将不胜感激。

func performGoogleQuery(url:URL)
{
    print("PERFORM GOOGLE QUERY")
    let task = URLSession.shared.dataTask(with: url, completionHandler: {(data, response, error) in
        if error != nil
        {
            print("An error occured: (error)")
            return
        }
        do {
            let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:Any]
            // Parse the json results into an array of MKMapItem objects
            if let places = json?["results"] as? [[String : Any]]
            {
                print("Places Count = (places.count)")     // Returns 20 on first pass and 0 on second.
                for place in places
                {
                    let name = place["name"] as! String
                    print("(name)")
                    if let geometry = place["geometry"] as? [String : Any]
                    {
                        if let location = geometry["location"] as? [String : Any]
                        {
                            let lat = location["lat"] as! CLLocationDegrees
                            let long = location["lng"] as! CLLocationDegrees
                            let coordinate = CLLocationCoordinate2DMake(lat, long)
                            let placemark = MKPlacemark(coordinate: coordinate)
                            let mapItem = MKMapItem(placemark: placemark)
                            mapItem.name = name
                            self.mapitems.append(mapItem)
                        }
                    }
                }
                print("mapItems COUNT = (self.mapitems.count)")    // Remains at 20 after 2 passes.
            }
            // If there is another page of results, 
            // configure the new url and run the query again.
            if let pageToken = json?["next_page_token"]
            {
                let newURL = URL(string: "https://maps.googleapis.com/maps/api/place/textsearch/json?pagetoken=(pageToken)&key=(self.googleAPIKey)")
                //print("PAGETOKENURL = (newURL)")
                self.performGoogleQuery(url: newURL!)
            }
        }catch {
            print("error serializing JSON: (error)")
        }
    })
     task.resume()
}

更新(基于迪玛的回应(:更改 self.performGoogleQuery(url: newURL!(

对此

let when = DispatchTime.now() + 2 // change 2 to desired number of seconds
            DispatchQueue.main.asyncAfter(deadline: when) {
                        self.performGoogleQuery(url: newURL!)
            }

根据文档:

发布next_page_token和 何时生效。

我认为您可能太快地获取下一页。尝试将延迟设置为至少几秒钟,看看是否可以解决您的问题。

从我所看到的情况来看,我认为您不应该快速连续自动获取页面。他们似乎希望您让用户触发获取其他内容。

您最多可以在原始页面之后请求新页面两次 查询。必须依次显示每页结果。两个或更多 搜索结果的页面不应显示为 单个查询。

最新更新