Add reverse geocoding service (#1085)

* add Geocoding service

* move url session extension
This commit is contained in:
Flescio
2023-06-15 16:40:42 +02:00
committed by GitHub
parent 2cfc844545
commit 163e38b1a9
12 changed files with 190 additions and 29 deletions
@@ -184,6 +184,9 @@ final class AppSettings {
let lightTileStaticMapStyleURL = "https://api.maptiler.com/maps/9bc819c8-e627-474a-a348-ec144fe3d810/{z}/{x}/{y}.png"
let darkTileStaticMapStyleURL = "https://api.maptiler.com/maps/dea61faf-292b-4774-9660-58fcef89a7f3/{z}/{x}/{y}.png"
// maptiler geocoding url
let geocodingURLFormatString = "https://api.maptiler.com/geocoding/%f,%f.json"
// MARK: - Feature Flags
// MARK: Start Chat
@@ -21,3 +21,9 @@ extension MapTilerStyleBuilder {
self.init(lightURL: appSettings.lightTileMapStyleURL, darkURL: appSettings.darkTileMapStyleURL, key: appSettings.mapTilerApiKey)
}
}
extension MapTilerGeoCodingService {
init(session: URLSession = .shared, appSettings: AppSettings) {
self.init(session: session, key: appSettings.mapTilerApiKey, geocodingURL: appSettings.geocodingURLFormatString)
}
}
@@ -0,0 +1,28 @@
//
// Copyright 2023 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
extension URLSession {
/// The same as `data(for:delegate:)` but with an additional immediate retry if the first attempt fails.
func dataWithRetry(for request: URLRequest, delegate: URLSessionTaskDelegate? = nil) async throws -> (Data, URLResponse) {
if let firstTryResult = try? await data(for: request, delegate: delegate) {
return firstTryResult
}
return try await data(for: request, delegate: delegate)
}
}
@@ -23,7 +23,7 @@ struct MapTilerAuthorization {
self.key = key
}
func authorizateURL(_ url: URL) -> URL {
func authorizeURL(_ url: URL) -> URL {
url.appending(queryItems: [URLQueryItem(name: "key", value: key)])
}
}
@@ -0,0 +1,27 @@
//
// Copyright 2023 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import CoreLocation
import Foundation
enum MapTilerGeocodingError: Error {
case wrongGeocodingURL
case geocodingFailed
}
protocol MapTilerGeoCodingServiceProtocol {
func reverseGeoCoding(for coordinate: CLLocationCoordinate2D) async -> Result<String, MapTilerGeocodingError>
}
@@ -0,0 +1,72 @@
//
// Copyright 2023 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import CoreLocation
import Foundation
struct MapTilerGeoCodingService: MapTilerGeoCodingServiceProtocol {
private let key: String
private let session: URLSession
private let geocodingURL: String
init(session: URLSession = .shared, key: String, geocodingURL: String) {
self.session = session
self.key = key
self.geocodingURL = geocodingURL
}
private struct GeocodedPlace: Decodable {
struct FeatureCollection: Decodable {
let placeName: String
}
let features: [FeatureCollection]
}
func reverseGeoCoding(for coordinate: CLLocationCoordinate2D) async -> Result<String, MapTilerGeocodingError> {
let latitude = coordinate.latitude
let longitude = coordinate.longitude
let path = String(format: geocodingURL, longitude, latitude)
guard var url = URL(string: path) else { return .failure(.wrongGeocodingURL) }
let authorization = MapTilerAuthorization(key: key)
url = authorization.authorizeURL(url)
url.append(queryItems: [.init(name: "limit", value: "1")])
var request = URLRequest(url: url)
request.httpMethod = "GET"
do {
let (data, response) = try await session.dataWithRetry(for: request)
guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
let errorDescription = String(data: data, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "Unknown"
MXLog.error("Failed to get reverse geocoding: \(errorDescription)")
MXLog.error("Response: \(response)")
return .failure(.geocodingFailed)
}
// Parse the JSON data
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let decodedResponse = try decoder.decode(GeocodedPlace.self, from: data)
guard let placeName = decodedResponse.features.first?.placeName else { return .failure(.geocodingFailed) }
return .success(placeName)
} catch {
return .failure(.geocodingFailed)
}
}
}
@@ -16,10 +16,6 @@
import Foundation
protocol MapTilerStyleBuilderProtocol {
func dynamicMapURL(for style: MapTilerStyle) -> URL?
}
struct MapTilerStyleBuilder: MapTilerStyleBuilderProtocol {
let lightURL: String
let darkURL: String
@@ -36,6 +32,6 @@ struct MapTilerStyleBuilder: MapTilerStyleBuilderProtocol {
guard let url = URL(string: path) else { return nil }
let authorization = MapTilerAuthorization(key: key)
return authorization.authorizateURL(url)
return authorization.authorizeURL(url)
}
}
@@ -0,0 +1,21 @@
//
// Copyright 2023 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
protocol MapTilerStyleBuilderProtocol {
func dynamicMapURL(for style: MapTilerStyle) -> URL?
}
@@ -342,14 +342,3 @@ extension BugReportService: URLSessionTaskDelegate {
.store(in: &cancellables)
}
}
private extension URLSession {
/// The same as `data(for:delegate:)` but with an additional immediate retry if the first attempt fails.
func dataWithRetry(for request: URLRequest, delegate: URLSessionTaskDelegate? = nil) async throws -> (Data, URLResponse) {
if let firstTryResult = try? await data(for: request, delegate: delegate) {
return firstTryResult
}
return try await data(for: request, delegate: delegate)
}
}