У меня есть еще одна проблема с наблюдаемыми объектами.
В моем View в строке «Position 1» у меня есть текстовое представление для редактирования адреса (и сохранения его в свойстве состояния «text», которое должно отображаться в представлении).
Переменная состояния "text" должна быть инициализирована из свойства LocationObserver класса "currentAddress". Я только что попытался установить инициализацию представления Может кто-нибудь мне помочь?
Заранее спасибо!
Best
Dragan
The View
struct PickFoto: View {
@ObservedObject var observeLocation = LocationObserver.shared()!
@State private var address = LocationObserver.shared()?.currentAddress ?? " "
...
TextView(text: $text, isEditing: $isEditing) // Position 1
Text("current Address (observeLocation): \(observeLocation.currentAddress)") // Position 2
...
}
The Shared Object
class LocationObserver: NSObject, CLLocationManagerDelegate, ObservableObject {
// This published property value has to be the initial value
// for the TextView (the property $text. how to to this??)
@Published var currentAddress = " "
static var instance: LocationObserver?
var locationManager = CLLocationManager()
var defaultLocation = CLLocation(latitude: 52.516861, longitude:13.356796)
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let currentLocation = locations.last?.coordinate
convertGPSToAdress(coordinates: locations.last ?? defaultLocation,
completion: { (retStr: String) in
self.currentAddress = retStr // set the @Published property
print("currentAddress in EscapingClosure: \(self.currentAddress)")
//everything is fine
}
)
}
func convertGPSToAdress(coordinates: CLLocation,
completion: @escaping(String) -> ()) -> () {
let address = CLGeocoder.init()
address.reverseGeocodeLocation(coordinates) { (places, error) in
if error == nil{
if places != nil {
let place = places?.first
completion(formatAddressString(place: place!)) // returns a formatted string address
}
}
}
}
....
}