I have the following code:
func mapView(_ mapView: MGLMapView, annotation: MGLAnnotation, calloutAccessoryControlTapped control: UIControl) {
var bus = [String]()
let headers = [
"content-type": "application/x-www-form-urlencoded",
"cache-control": "no-cache",
"postman-token": "23cb4108-e24b-adab-b979-e37fd8f78622"
]
let postData = NSMutableData(data: "bus_stop=Science Hill".data(using: String.Encoding.utf8)!)
let request = NSMutableURLRequest(url: NSURL(string: "https://ucsc-bts3.soe.ucsc.edu/bus_stops/inner_eta.php?%22bus_stop%22=%22Science%20Hill%22")! as URL,
cachePolicy: .reloadIgnoringLocalAndRemoteCacheData,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error!)
} else {
_ = response as? HTTPURLResponse
}
do {
let jsonObject = try JSONSerialization.jsonObject(with: data!)
guard let jsonArray = jsonObject as? [String: Any] else{
print("JsonSerialization Failed")
return
}
if let etaTableRows = jsonArray["rows"] as? NSArray{
for etaData in etaTableRows{
let etaDictionary = etaData as? NSDictionary
bus.append(etaDictionary!["bus_type"] as! String)
}
}
} catch {
print("JSONSerialization error:", error)
}
})
dataTask.resume()
print(bus) //bus array should be updated here
mapView.deselectAnnotation(annotation, animated: false)
let schedule = ScheduleVC()
schedule.data.append(annotation.title!! + " ETAs")
self.present(schedule, animated: true, completion: nil)
}
It appears that print(bus) is being run before the http response is received and bus array is filled. My goal would be to fill the bus array with the http response data, then print it. I'm not sure how to accomplish this.