Skip to content

Commit

Permalink
feat: add new extensions for CoreLocation
Browse files Browse the repository at this point in the history
  • Loading branch information
gtokman committed May 3, 2021
1 parent 1fb4ed0 commit b7cc732
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 0 deletions.
36 changes: 36 additions & 0 deletions Sources/ExtensionKit/CoreLocation/CLLocation.swift
@@ -0,0 +1,36 @@
import CoreLocation
import Combine

public extension CLLocation {

/// `CLLocation` from `CLLocationCoordinate2D`
/// - Parameter coordinate: `CLLocationCoordinate2D`
convenience init(from coordinate: CLLocationCoordinate2D) {
self.init(latitude: coordinate.latitude, longitude: coordinate.longitude)
}

/// Geocode location `Error`
enum GeocodeError: Error {
case invalid(String)
case empty(String)
}

/// Reverse geocode a `CLLocation`
/// - Parameter location: `CLLocation`
/// - Returns: Future with Result<[`CLPlacemark`], `GeocodeError`>
func reverseGeocode(location: CLLocation) -> Deferred<Future<[CLPlacemark], GeocodeError>> {
Deferred {
Future { promise in
CLGeocoder().reverseGeocodeLocation(location) { placemarks, error -> Void in
if let err = error {
return promise(.failure(.invalid("\(String(describing: err))")))
}
guard let marks = placemarks, !marks.isEmpty else {
return promise(.failure(.empty("\(String(describing: placemarks))")))
}
return promise(.success(marks))
}
}
}
}
}
35 changes: 35 additions & 0 deletions Sources/ExtensionKit/CoreLocation/CLLocationCoordinate2D.swift
@@ -0,0 +1,35 @@
import CoreLocation

extension CLLocationCoordinate2D: Equatable {

/// Equatable coordinates
public static func == (lhs: CLLocationCoordinate2D, rhs: CLLocationCoordinate2D) -> Bool {
lhs.latitude == rhs.latitude && lhs.longitude == rhs.longitude
}

}

extension CLLocationCoordinate2D: Codable {

/// `CLLocationCoordinate2D` at (latitude: 0, longitude 0)
public static let zero = CLLocationCoordinate2D(latitude: 0, longitude: 0)

/// Encode a `CLLocationCoordinate2D`
/// - Parameter encoder: Encoder
/// - Throws: `EncodingError`
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
try container.encode(longitude)
try container.encode(latitude)
}

/// Decode `CLLocationCoordinate2D` from data
/// - Parameter decoder: Decoder
/// - Throws: `DecodingError`
public init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
let longitude = try container.decode(CLLocationDegrees.self)
let latitude = try container.decode(CLLocationDegrees.self)
self.init(latitude: latitude, longitude: longitude)
}
}

0 comments on commit b7cc732

Please sign in to comment.