1
Im新的Swift,我試圖使用Google Directions API。我修改了一個函數來獲取Polyline並將Google方向放入數組中。我聲明爲我正在使用的類的屬性的方向數組,因此可以將結果顯示在表中。我已經檢查過,並且數組被正確填充了閉包內的方向。但是,當我嘗試在CellForTableAT函數的閉包外使用它時,它是空的。我可能沒有正確地從關閉數據中獲取數據,但我無法弄清楚。我開始構建我數組中// MARK:使用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)
}
}