2017-01-14 5 views
1

Swiftには新しく、Google Directions APIを使用しようとしています。私はPolylineを取得し、Googleの指示を配列に入れる関数を変更しました。私が作業しているクラスのプロパティとして宣言した指示配列は、結果をテーブルに表示することができます。私はチェックして、配列はクロージャの中の指示に適切に入力されます。しかし、CellForTableAT関数のクロージャの外側でそれを使用しようとすると、空になります。私はおそらくクロージャのデータを正しく取得していないが、私はそれを把握できません。閉鎖へ - (>([方向]))と、それの外のデータにアクセスすることができた私はリターンを追加スタートビル行き方アレイをswiftyJasonGoogle Driections APIは、Swift 3のクロージャーから配列を返します。

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


} 

答えて

0

を使用して:私は// MARKで私の配列の構築を開始します。

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

このようにするのがベストプラクティスであるかどうかはわかりませんが、私はテーブルに表示するデータが必要です。

関連する問題