I'm trying to use the MapKit Directions Request to get transit directions between two coordinates.
When I switch to other (non-Transit) types, the code below works, but when I switch to Transit, it throws an error that doesn't show up anywhere in Apple's documentation.
The two locations (source and destination) are both in New York City so there should definitely be transit directions available.
Error message:
Error Domain=MKErrorDomain Code=5 "(null)"
Code snippet:
override func viewDidLoad() {
super.viewDidLoad()
let request = MKDirectionsRequest()
// Set request parameters
request.source = MKMapItem(placemark: MKPlacemark(coordinate: CLLocationCoordinate2D(latitude: 40.7127, longitude: -74.0059), addressDictionary: nil))
request.destination = MKMapItem(placemark: MKPlacemark(coordinate: CLLocationCoordinate2D(latitude: 40.6761, longitude: -73.9521), addressDictionary: nil))
request.requestsAlternateRoutes = true
// Set tranport type parameter (anything other than .Transit works)
request.transportType = .Transit
let directions = MKDirections(request: request)
directions.calculateDirectionsWithCompletionHandler { response, error in
print(response)
guard let routes = response?.routes else {
print(error?.description)
return
}
// Prints step-by-step directions
for r in routes {
print("New route")
for step in r.steps {
print(" " + step.instructions)
}
}
}
}
Any advice on what I might be doing wrong for the particular Transit case? Thank you!
Routing directions for transit is currently not supported (iOS 9). MKDirectionsRequest
will return a null error, as you observed.
This only seems to be documented directly in MapKit's headers. Take a look at the comment for the Transit
type.
// MKDirectionsTypes.h
@available(iOS 7.0, *)
public struct MKDirectionsTransportType : OptionSetType {
public init(rawValue: UInt)
public static var Automobile: MKDirectionsTransportType { get }
public static var Walking: MKDirectionsTransportType { get }
@available(iOS 9.0, *)
public static var Transit: MKDirectionsTransportType { get } // Only supported for ETA calculations
public static var Any: MKDirectionsTransportType { get }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With