【问题标题】:Google Driections API return an array from the closure in Swift 3Google Driections API 从 Swift 3 的闭包中返回一个数组
【发布时间】:2017-01-14 22:41:06
【问题描述】:

我是 Swift 新手,我正在尝试使用 Google Directions API。我修改了一个函数来获取折线并将谷歌方向放入一个数组中。我声明为我正在使用的类的属性的方向数组,因此我可以在表格中显示结果。我已经检查过,并且该数组已正确填充了闭包内的方向。但是,当我尝试在 CellForTableAT 函数的闭包之外使用它时,它是空的。我可能没有正确地从闭包中获取数据,但我无法弄清楚。我在 //MARK 开始构建我的数组:使用 swiftyJason 开始构建方向数组

func getDirections(currentDestination: GMSMarker, origin: String!, destination: String!, waypoints:    Array<String>!, mode: String!, completionHandler: ((_ status:   String, _ success: Bool) -> Void)?) {

    if let originLocation = origin {
        if let destinationLocation = destination {
            var directionsURLString = baseURLDirections + "origin=" + originLocation + "&destination=" + destinationLocation + "&mode=" + mode
            if let routeWaypoints = waypoints {
                directionsURLString += "&waypoints=optimize:true"

                for waypoint in routeWaypoints {
                    directionsURLString += "|" + waypoint
                }
            }


            directionsURLString = ("\(directionsURLString)&sensor=true&key=???????????????")
            print("directons*******")
            print(directionsURLString)

            directionsURLString = directionsURLString.addingPercentEscapes(using: String.Encoding.utf8)!
            let directionsURL = NSURL(string: directionsURLString)
            DispatchQueue.main.async( execute: { () -> Void in
                let directionsData = NSData(contentsOf: directionsURL! as URL)
                do{
                    let dictionary: Dictionary<String, AnyObject> = try JSONSerialization.jsonObject(with: directionsData! as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as! Dictionary<String, AnyObject>

                    let status = dictionary["status"] as! String

                    let json = JSON(data: directionsData as! Data)


                    if status == "OK" {
                        self.selectedRoute = (dictionary["routes"] as! Array<Dictionary<String, AnyObject>>)[0]
                        self.overviewPolyline = self.selectedRoute["overview_polyline"] as! Dictionary<String, AnyObject>

                        let legs = self.selectedRoute["legs"] as! Array<Dictionary<String, AnyObject>>

                        let startLocationDictionary = legs[0]["start_location"] as! Dictionary<String, AnyObject>
                        self.originCoordinate = CLLocationCoordinate2DMake(startLocationDictionary["lat"] as! Double, startLocationDictionary["lng"] as! Double)

                        let endLocationDictionary = legs[legs.count - 1]["end_location"] as! Dictionary<String, AnyObject>
                        self.destinationCoordinate = CLLocationCoordinate2DMake(endLocationDictionary["lat"] as! Double, endLocationDictionary["lng"] as! Double)

                        let originAddress = legs[0]["start_address"] as! String
                        let destinationAddress = legs[legs.count - 1]["end_address"] as! String

                        for (index, leg) in json["routes"][0]["legs"].arrayValue.enumerated()  {
                            var count = 0
  //MARK: Start Building Directions Array 

                            for (stepIndex, step) in json["routes"][0]["legs"][index]["steps"].arrayValue.enumerated() {
                                count += 1

                                let htmlInstructions = json["routes"][0]["legs"][index]["steps"][stepIndex]["html_instructions"].string
                                let distance = json["routes"][0]["legs"][index]["steps"][stepIndex]["distance"]["text"].string
                                let duration = json["routes"][0]["legs"][index]["steps"][stepIndex]["duration"]["text"].string

                                let direction:Direction = Direction(index: count, htmlInstructions: htmlInstructions, distance: distance, duration: duration)

                                self.directions.append(direction)

                            }
                            self.tableView.reloadData()
                        }
                        //end of stepts to get writtine directions



                        //NOT Plotting markers endpoins
                        //position markers for ployline endpoints
                        //let originMarker = GMSMarker(position: self.originCoordinate)
                       // originMarker.map = self.mapView
                        //originMarker.icon = UIImage(named: "mapIcon")
                       // originMarker.title = originAddress


                          self.destinationMarker = currentDestination


                      //  destinationMarker.map = self.mapView
                     //   destinationMarker.icon = UIImage(named: "mapIcon")
                     //   destinationMarker.title = destinationAddress
                     //   destinationMarker.icon = GMSMarker.markerImage(with: UIColor.green)

                        if waypoints != nil && waypoints.count > 0 {
                            for waypoint in waypoints {
                                let lat: Double = (waypoint.components(separatedBy: ",")[0] as NSString).doubleValue
                                let lng: Double = (waypoint.components(separatedBy: ",")[1] as NSString).doubleValue

                                let marker = GMSMarker(position: CLLocationCoordinate2DMake(lat, lng))
                                marker.map = self.mapView
                                marker.icon = UIImage(named: "mapIcon")

                            }
                        }

                        self.routePolyline.map = nil

                        let route = self.overviewPolyline["points"] as! String

                        let path: GMSPath = GMSPath(fromEncodedPath: route)!
                        self.routePolyline = GMSPolyline(path: path)
                        self.routePolyline.map = self.mapView
                        self.routePolyline.strokeColor = UIColor.red
                        self.routePolyline.strokeWidth = 3.0

                        //Fit map to entire polyline

                        var bounds = GMSCoordinateBounds()

                        for index in 1...path.count() {
                            bounds = bounds.includingCoordinate(path.coordinate(at: index))
                        }

                        self.mapView.animate(with: GMSCameraUpdate.fit(bounds))

                        // end of fit map to ployline


                    }
                    else {
                        print("status of poly draw")
                        //completionHandler(status: status, success: false)
                    }
                }
                catch {
                    print("catch")

                    // completionHandler(status: "", success: false)
                }
            })
        }
        else {
            print("Destination is nil.")
            //completionHandler(status: "Destination is nil.", success: false)
        }
    }
    else {
        print("Origin is nil")
        //completionHandler(status: "Origin is nil", success: false)
    }


}

【问题讨论】:

    标签: google-maps swift3 closures google-directory-api


    【解决方案1】:

    我在闭包中添加了一个 return (->([Direction])) 并且能够访问它之外的数据。

    func getDirections(currentDestination: GMSMarker, origin: String!, destination: String!, waypoints:    Array<String>!, mode: String!, completionHandler: ((_ status:   String, _ success: Bool) -> Void)?) -> ([Direction])
    

    我是新手,所以不确定这样做是否是最佳做法,但我需要将数据显示在表格中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多