ios – Awaiting Process Completion in SwiftUI View

I’m working with a view that shows an inventory of places. When a person faucets on a location, a didSet block containing a Process is triggered in a separate class wrapped with the @ObservedObject property:

struct LocationSearch: View {
    @StateObject var locationService = LocationService()
    @IbservedObject var networking: Networking
    var savedLocations = SavedLocations()
    var physique: some View {
        ForEach(locationService.searchResults, id: .self) { location in
            Button(location.title) {
                getCoordinate(addressString: location.title) { coordinates, error in
                    if error == nil {
                        networking.lastLocation = CLLocation(latitude: coordinates.latitude, longitude: coordinates.longitude)
                        // await networking.locationString to replace
                        // this smells unsuitable
                        // how one can higher await Process completion in didSet?
                        DispatchQueue.predominant.asyncAfter(deadline: .now() + 1) {
                            UserDefaults.customary.set(savedLocations.all, forKey: "savedLocations")

The Process that will get triggered after netowrking.lastLocation is ready is as follows:

class Networking: NSObject, ObservableObject, CLLocationManagerDelegate {
    @Revealed public var lastLocation: CLLocation? {
        didSet {
            Process {
                getLocationString() { placemark in
                    self.locationString = placemark
                getMainWeather(self.lastLocation?.coordinate.latitude ?? 0, self.lastLocation?.coordinate.longitude ?? 0)
                getAQI(self.lastLocation?.coordinate.latitude ?? 0, self.lastLocation?.coordinate.longitude ?? 0)

What’s a greater method to make sure that the duty has had time to finish and that the brand new string will probably be saved to UserDefaults versus freezing my software’s UI for one second?

In case it is not clear, if I do not await one second, as a substitute of the brand new worth of locationString being saved to UserDefaults, the previous worth is saved as a substitute as a result of the logic within the didSet block hasn’t had time to finish.

See also  Enabling Developer Mode in iOS 16 for Xcode Improvement

Leave a Reply