Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix batch geocoding request handling #148

Merged
merged 17 commits into from
Jul 12, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 96 additions & 0 deletions MapboxGeocoder.xcodeproj/project.pbxproj

Large diffs are not rendered by default.

8 changes: 8 additions & 0 deletions MapboxGeocoder/MBGeocodeOptions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,11 @@ open class GeocodeOptions: NSObject {
*/
internal var queries: [String] = []

/**
The query mode of the forward or reverse geocoding request.
*/
internal var mode = "mapbox.places"

/**
An array of URL parameters to include in the request URL.
*/
Expand Down Expand Up @@ -221,6 +226,7 @@ open class ForwardBatchGeocodeOptions: ForwardGeocodeOptions, BatchGeocodeOption
*/
@objc public override init(queries: [String]) {
super.init(queries: queries)
mode = "mapbox.places-permanent"
}
}

Expand All @@ -236,6 +242,7 @@ open class ReverseBatchGeocodeOptions: ReverseGeocodeOptions, BatchGeocodeOption
*/
@objc public override init(coordinates: [CLLocationCoordinate2D]) {
super.init(coordinates: coordinates)
mode = "mapbox.places-permanent"
}

/**
Expand All @@ -245,5 +252,6 @@ open class ReverseBatchGeocodeOptions: ReverseGeocodeOptions, BatchGeocodeOption
*/
@objc public convenience init(locations: [CLLocation]) {
self.init(coordinates: locations.map { $0.coordinate })
mode = "mapbox.places-permanent"
}
}
52 changes: 39 additions & 13 deletions MapboxGeocoder/MBGeocoder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,17 @@ open class Geocoder: NSObject {
let decoder = JSONDecoder()

do {
let result = try decoder.decode([GeocodeResult].self, from: data)

let result: [GeocodeResult]

do {
// Decode multiple batch geocoding queries
result = try decoder.decode([GeocodeResult].self, from: data)
} catch {
// Decode single batch geocding queries
result = [try decoder.decode(GeocodeResult.self, from: data)]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As tail work, maybe we should consider refactoring Geocoder’s public methods so that we distinguish between single-serving and batched requests at different places in the call stack.

}

let placemarks = result.map { $0.placemarks }
let attributionsByQuery = result.map { $0.attribution }
completionHandler(placemarks, attributionsByQuery, nil)
Expand All @@ -250,16 +260,20 @@ open class Geocoder: NSObject {
*/
fileprivate func dataTaskWithURL(_ url: URL, completionHandler: @escaping (_ data: Data?) -> Void, errorHandler: @escaping (_ error: NSError) -> Void) -> URLSessionDataTask {
var request = URLRequest(url: url)

request.setValue(userAgent, forHTTPHeaderField: "User-Agent")
return URLSession.shared.dataTask(with: request) { (data, response, error) in

guard let data = data else { return }
let decoder = JSONDecoder()

do {
let result = try decoder.decode(GeocodeAPIResult.self, from: data)
guard result.message == nil else {
let apiError = Geocoder.descriptiveError(["message": result.message!], response: response, underlyingError: error as NSError?)
// Handle multiple batch geocoding queries
let result = try decoder.decode([GeocodeAPIResult].self, from: data)

// Check if any of the batch geocoding queries failed
if let failedResult = result.first(where: { $0.message != nil }) {
let apiError = Geocoder.descriptiveError(["message": failedResult.message!], response: response, underlyingError: error as NSError?)
DispatchQueue.main.async {
errorHandler(apiError)
}
Expand All @@ -269,8 +283,26 @@ open class Geocoder: NSObject {
completionHandler(data)
}
} catch {
DispatchQueue.main.async {
errorHandler(error as NSError)
// Handle single & single batch geocoding queries
do {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Per chat with @1ec5 we may want to consider doing a refactor of this gnarly do/try/catch block.

let result = try decoder.decode(GeocodeAPIResult.self, from: data)
// Check if geocoding query failed
if let message = result.message {
let apiError = Geocoder.descriptiveError(["message": message], response: response, underlyingError: error as NSError?)
DispatchQueue.main.async {
errorHandler(apiError)
}
return

}
DispatchQueue.main.async {
completionHandler(data)
}
} catch {
// Handle errors that don't return a message (such as a server/network error)
DispatchQueue.main.async {
errorHandler(error as NSError)
}
}
}
}
Expand All @@ -290,13 +322,7 @@ open class Geocoder: NSObject {

assert(!options.queries.isEmpty, "No query")

let mode: String
if options.queries.count > 1 {
mode = "mapbox.places-permanent"
assert(options.queries.count <= 50, "Too many queries in a single request.")
} else {
mode = "mapbox.places"
}
let mode = options.mode

let queryComponent = options.queries.map {
$0.replacingOccurrences(of: " ", with: "+")
Expand Down
Loading