i'm trying calculate eta between 2 coordinates in swift using calculateetawithcompletionhandler mkdirections class. have following code in program,
mapviewcontroller.swift
print("a") calculateetaofclosestbus(closestbusstop) print("b") func calculateetaofclosestbus(destination: busstop) { var shortesteta = 0 print("c") var request = mkdirectionsrequest() var sourceitem = mkmapitem(placemark: mkplacemark(coordinate: listbuses[0].pin.coordinate, addressdictionary: nil)) request.source = sourceitem request.transporttype = .automobile let destinationcoordinates = cllocationcoordinate2d(latitude: destination.coordinate.latitude, longitude: destination.coordinate.longitude) let destinationitem = mkmapitem(placemark: mkplacemark(coordinate: destinationcoordinates, addressdictionary: nil)) request.destination = destinationitem request.requestsalternateroutes = false var directions = mkdirections(request: request) print("d") directions.calculateetawithcompletionhandler { (etaresponse, error) -> void in print("e") if let error = error { print("error while requesting eta : \(error.localizeddescription)") } else { print("f") shortesteta = int((etaresponse?.expectedtraveltime)!) } } print("g") }
i included print statements show execution of code. when run program, output is
a c d g b e f
so, i've noticed calculateetaofclosestbus() function finishes executing (reaches g, b), directions.calculateetawithcompletionhandler executes, 'e' , 'f' printed after we've returned calculateetaofclosestbus().
i'm sure don't understand how calculateetawithcompletionhandler works, calculate eta between 2 annotations via automobile , if there more intuitive way accomplish or if me understand handler better, appreciated.
solution:
ios - swift - function returns asynchronously retrieved value helped me understand how accomplish best.
please ath link states calculateetawithcompletionhandler
works asynchronously .since asynchronous, works on different thread.but main thread executing on own way , prints g
begins calculating requested travel-time information asynchronously.
if return in asynchronous method..you can using closure.here link
Comments
Post a Comment