Google提供网络服务:如何在Swift 3中获得结果的下一页 [英] Google places web service: How to get next page of results in Swift 3

查看:97
本文介绍了Google提供网络服务:如何在Swift 3中获得结果的下一页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在iOS应用中使用Google Web Service API来查找用户所在位置附近的临终关怀地点。我可以得到结果的第一页,但使用pagetoken检索下一页结果失败。以下是我的搜索功能。任何帮助我去哪里错了(从来没有使用URLSession之前),将不胜感激。

  func performGoogleQuery(url:URL) 
print $ {
print(PERFORM GOOGLE QUERY)
让task = URLSession.shared.dataTask(with:url,completionHandler:{(data,response,error)in
$
print(发生错误:\(错误))
返回
}

{
让json = try JSONSerialization.jsonObject(with:data !, options:.allowFragments)as?[String:Any]

//将json结果解析为一个MKMapItem对象数组
如果let places = json?[results] as?[[String:Any]]
{
print(Places Count = \(places.count))//第一阶段返回20,第二阶段返回0。

用于放置场所
{
let name = place [name] as!String
print(\(name))

如果let geometry = place [geometry] as? [字符串:任何]
{
如果让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)



$ b print(mapItems COUNT = \(self.mapitems.count) )//在2次传球后保持在20。
}
//如果有另一页结果,
//配置新的url并再次运行查询。
如果让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。 (错误序列化JSON:\(错误))
}
})
task.resume()
}




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


至此

  let when = DispatchTime.now()+ 2 //将2更改为所需的秒数
DispatchQueue.main.asyncAfter(截止日期:何时){
self.performGoogleQuery(url:newURL!)
}
解决方案

rel =nofollow noreferrer> documentation:


发布next_page_token和$

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



从我看到的,我不认为你的意思是自动快速连续提取页面。他们似乎希望您让用户触发获取更多内容。


您可以请求一个新页面,最多两次
查询。每页结果都必须依次显示。
单个查询的结果不应显示两个或更多
页面的搜索结果。



I'm using the Google Web Service API in my iOS app to find hospice locations near the user's location. I can get the first page of results, but have been unsuccessful with using the pagetoken to retrieve the next page of results. Below is my search function. Any help on where I am going wrong (have never used URLSession before) would be appreciated.

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()
}

Update (Based on Dima's response): Change self.performGoogleQuery(url: newURL!)

to this

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

解决方案

According to the documentation:

There is a short delay between when a next_page_token is issued, and when it will become valid.

I think you are probably fetching the next page too quickly. Try to set a delay of at least a few seconds and see if that solves your issue.

From what I see though, I don't think you're meant to automatically fetch pages in quick succession. They seem to want you to let the user trigger fetching of additional content.

You can request a new page up to two times following the original query. Each page of results must be displayed in turn. Two or more pages of search results should not be displayed as the result of a single query.

这篇关于Google提供网络服务:如何在Swift 3中获得结果的下一页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆