Skip to content

Commit e41f9a5

Browse files
authored
Only reverse-geocode each TKNamedCoordinate once (#409)
1 parent 1a62a55 commit e41f9a5

File tree

1 file changed

+34
-18
lines changed

1 file changed

+34
-18
lines changed

Sources/TripKit/model/TKNamedCoordinate.swift

Lines changed: 34 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ import MapKit
1111

1212
open class TKNamedCoordinate : NSObject, NSSecureCoding, Codable, TKClusterable {
1313

14+
public static var enableReverseGeocodingAddress: Bool = true
15+
1416
public fileprivate(set) var coordinate: CLLocationCoordinate2D {
1517
didSet {
1618
_address = nil
@@ -42,29 +44,21 @@ open class TKNamedCoordinate : NSObject, NSSecureCoding, Codable, TKClusterable
4244
private var _placemark: CLPlacemark? = nil
4345
@objc public var placemark: CLPlacemark? {
4446
if let placemark = _placemark { return placemark }
45-
guard coordinate.isValid else { return nil }
46-
47-
let location = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)
48-
let geocoder = CLGeocoder()
47+
guard coordinate.isValid, TKNamedCoordinate.enableReverseGeocodingAddress, reverseGeocodingTask == nil else { return nil }
4948

50-
// no weak self as we're not retaining the geocoder
51-
geocoder.reverseGeocodeLocation(location) { placemarks, error in
52-
guard let placemark = placemarks?.first else { return }
53-
54-
self._placemark = placemark
55-
self._address = placemark.address()
56-
57-
// KVO
58-
if self.name != nil {
59-
self.subtitle = ""
60-
} else {
61-
self.title = ""
49+
let coordinate = self.coordinate
50+
reverseGeocodingTask = Task { [weak self] in
51+
let location = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)
52+
let geocoder = CLGeocoder()
53+
if let best = try? await geocoder.reverseGeocodeLocation(location).first {
54+
self?.assignPlacemark(best, includeName: false)
6255
}
6356
}
64-
65-
return _placemark
57+
return nil
6658
}
6759

60+
private var reverseGeocodingTask: Task<Void, Never>?
61+
6862
@objc public var locationID: String? = nil
6963
@objc public var timeZoneID: String? = nil
7064

@@ -118,6 +112,28 @@ open class TKNamedCoordinate : NSObject, NSSecureCoding, Codable, TKClusterable
118112
convenience init(from: TKAPI.Location) {
119113
self.init(latitude: from.lat, longitude: from.lng, name: from.name, address: from.address)
120114
}
115+
116+
public func assignPlacemark(_ placemark: CLPlacemark, includeName: Bool) {
117+
if includeName {
118+
if let name = placemark.name {
119+
self.name = name
120+
} else if let poi = placemark.areasOfInterest?.first {
121+
self.name = poi
122+
} else {
123+
self.name = nil
124+
}
125+
}
126+
127+
_address = placemark.address()
128+
_placemark = placemark
129+
130+
// KVO
131+
if self.name != nil {
132+
self.subtitle = ""
133+
} else {
134+
self.title = ""
135+
}
136+
}
121137

122138
// MARK: - Codable
123139

0 commit comments

Comments
 (0)