How to wait for another value to be assigned to run .onAppear?

Viewed 470

I am learning to develop apps for iOS from scratch. And I chose SwiftUI to make an app that gets the location of the user, get with geocode the city where he is and with that information obtained, show a list of items that belong to that city from a API.

So, I learned on one hand how to get the location and on the other hand how to display a list. My problem now is that when you run .onAppear(perform: loadData) to display my list, the "city" result is still empty. Evidently the value of city is obtained after I try to display the list of the city.

Both the algorithm I have to get the location and the one I have to show the list work separately.

So my code is:

import SwiftUI

struct Response: Codable {
    var cinemas: [Cinema]
}

struct Cinema: Codable {
    var _id: String
    var cinemaName: String
    var cinemaCategory: String
}

struct HomeScreenView: View {
    
    @State var results = [Cinema]()
    
    @ObservedObject var lm = LocationManager()

    var latitude: String  {
        return("\(lm.location?.latitude ?? 0)") }
    var longitude: String { return("\(lm.location?.longitude ?? 0)") }
    var placemark: String { return("\(lm.placemark?.description ?? "XXX")") }
    var status: String    { return("\(lm.status)") }
    
    var city: String {
        return("\(lm.placemark?.locality ?? "empty")")
    }
    
    var body: some View {
        VStack {
            List(results, id: \._id) { item in
                VStack(alignment: .leading) {
                    Text(item.cinemaName)
                        .font(.headline)
                    Text(item.cinemaCategory)
                }
            }.onAppear(perform: loadData)
        }
        
    }
    
    func loadData() {
        guard let url = URL(string: "https://mycinemasapi.com/cinemasbycity/\(self.city)") else {
            print("Invalid URL")
            return
        }
        
        let request = URLRequest(url: url)
        
        URLSession.shared.dataTask(with: request) { data, response, error in
            
            if let data = data {
                if let decodedResponse = try? JSONDecoder().decode(Response.self, from: data) {
                    // we have good data – go back to the main thread
                    DispatchQueue.main.async {
                        // update our UI
                        self.results = decodedResponse.cinemas
                    }
                    
                    // everything is good, so we can exit
                    return
                }
            }
            
            // if we're still here it means there was a problem
            print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
            
        }.resume()
    }
}

UPDATE: LocationManager class

import Foundation
import CoreLocation
import Combine

class LocationManager: NSObject, ObservableObject {
  private let locationManager = CLLocationManager()
  private let geocoder = CLGeocoder()
  let objectWillChange = PassthroughSubject<Void, Never>()

  @Published var status: CLAuthorizationStatus? {
    willSet { objectWillChange.send() }
  }

  @Published var location: CLLocation? {
    willSet { objectWillChange.send() }
  }

  override init() {
    super.init()

    self.locationManager.delegate = self
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
    self.locationManager.requestWhenInUseAuthorization()
    self.locationManager.startUpdatingLocation()
  }

    
  @Published var placemark: CLPlacemark? {
    willSet { objectWillChange.send() }
  }

  private func geocode() {
    guard let location = self.location else { return }
    geocoder.reverseGeocodeLocation(location, completionHandler: { (places, error) in
      if error == nil {
        self.placemark = places?[0]
      } else {
        self.placemark = nil
      }
    })
  }
}

extension LocationManager: CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        self.status = status
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.last else { return }
        self.location = location
        self.geocode()
    }
}
1 Answers

As by your code just do load data on placemark received, like

        List(results, id: \._id) { item in
            VStack(alignment: .leading) {
                Text(item.cinemaName)
                    .font(.headline)
                Text(item.cinemaCategory)
            }
        }.onReceive(lm.$placemark) {
            if $0 != nil {
               self.loadData()
            }
        }
Related