简体   繁体   English

等待谷歌的地方要求

[英]wait for google places request

I would like to perform request in swift for google places api and after i will get the results i would like to store them in a tableview. 我想对Google Places api 快速执行请求,获得结果后,我想将它们存储在tableview中。 I think i resolved this in an unorthodox way. 我认为我以非正统的方式解决了这个问题。 I used dispatch_time for 6 seconds (that is the time the request needs to get all the data) but after i put them in a table view the table view has lag and is moving slow. 我使用了dispatch_time 6秒钟(即请求需要获取所有数据的时间),但是在将它们放入表视图之后,表视图滞后并且移动缓慢。 I want to do this the right way . 我想以正确的方式做这件事。 Does anyone know how ? 有人知道吗?

this is what i tried : 这是我尝试的:

self.fetchPlacesNearCoordinate(self.locValue1, radius: 1000, name: "food") self.fetchPlacesNearCoordinate(self.locValue1,半径:1000,名称:“食物”)

      showActivityIndicator()
        let delay = 6 * Double(NSEC_PER_SEC)
        let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
        dispatch_after(time, dispatch_get_main_queue()) {
           self.activities()
            self.hideActivityIndicator()

        }

where fetchPlacesNearCoordinate() is my function that makes the request for the google places api 其中fetchPlacesNearCoordinate()是我的函数,用于请求Google Places API

EDIT 1 编辑1

this is how it is implemented the fetchPlacesNearCoordinate() function: 这是fetchPlacesNearCoordinate()函数的实现方式:

func fetchPlacesNearCoordinate(coordinate: CLLocationCoordinate2D, radius: Double, name : String) { var urlString = " https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=(locValue1.latitude),(locValue1.longitude)&rankby=distance&types=food " urlString += "&key=(apiServerKey)" urlString = urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)! func fetchPlacesNearCoordinate(coordinate:CLLocationCoordinate2D,radius:Double,name:String){var urlString =“ https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=(locValue1.latitude),(locValue1 .longitude)&rankby = distance&types = food “ urlString + =”&key =(apiServerKey)“ urlString = urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!

    var placesTask = session.dataTaskWithURL(NSURL(string: urlString)!)

    if placesTask.taskIdentifier > 0 && placesTask.state == .Running {
        placesTask.cancel()
    }

    UIApplication.sharedApplication().networkActivityIndicatorVisible = true

    do{

        //******************Here's the line that displays error
        placesTask = session.dataTaskWithURL(NSURL(string: urlString)!) {
            (data, response, error) -> Void in
            UIApplication.sharedApplication().networkActivityIndicatorVisible = false
            //var placesArray = [GooglePlace]()
            do {
                if let json = try NSJSONSerialization.JSONObjectWithData(data!, options:[]) as? NSDictionary {
                    if let results = json["results"] as? NSArray {
                        for rawPlace:AnyObject in results {
                           // print(rawPlace)
                            var placename = ""
                            if let name = rawPlace["name"] as? NSString {
                                placename = name as String
                                self.locuri.insert(placename, atIndex: self.ct)
                                //self.locuri[ct] = placename

                            }
                            if let strada = rawPlace["vicinity"] as? NSString {
                                self.strazi.insert(strada as String, atIndex: self.ct)
                            }
                            if let iconurl = rawPlace["icon"] as? NSString {
                                self.iconuri.insert(iconurl as String, atIndex: self.ct)
                            }
                            if let placeid = rawPlace["place_id"] as? NSString {
                                self.placeiduri.insert(placeid as String, atIndex: self.ct)
                            }
                            self.ct++
                        }
                    }
                }
            } catch {
                //handle error
            }

        }


    }

    placesTask.resume()
}

here it is how and when i insert data to tableview 这里是如何,当我插入数据的tableview

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if (tableView == self.tblNearby){ func tableView(tableView:UITableView,cellForRowAtIndexPath indexPath:NSIndexPath)-> UITableViewCell {如果(tableView == self.tblNearby){

        let cell2 = tableView.dequeueReusableCellWithIdentifier("mycell", forIndexPath: indexPath) as! MyCustomCellTableViewCell
        cell2.myTitleLabel.text = locuri[indexPath.row]
        cell2.StreetLabel.text = strazi[indexPath.row]
        if (iconuri.count != 0){
            if let url = NSURL(string: iconuri[indexPath.row]) {
                if let data = NSData(contentsOfURL: url){
                    //cell2.myImage.contentMode = UIViewContentMode.ScaleAspectFit
                    cell2.myImage.image = UIImage(data: data)
                }
            }
        }

You should have a method that look like this 您应该有一个看起来像这样的方法

func loadPlaces() {
    startActivityIndicator()
    dataProvider.fetchPlacesNearCoordinate(coordinate, radius:searchRadius, types: searchedTypes) { places in
        stopActivityIndicator()
        //append places object to your data
        self.tableView.reloadData()
      }
}

However if the fetchPlacesNearCoordinate method does not dispatch the call of the clojure/completionBlock to the main queue then it should look like this 但是,如果fetchPlacesNearCoordinate方法没有将clojure / completionBlock的调用分派到主队列,则它应该看起来像这样

    func loadPlaces() {
        startActivityIndicator()
        dataProvider.fetchPlacesNearCoordinate(coordinate, radius:searchRadius, types: searchedTypes) { places in

            dispatch_async(dispatch_get_main_queue()) {
                stopActivityIndicator()
               //append places object to your data
               self.tableView.reloadData()
            }

        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM