如何等待分配另一个值以运行.onAppear?

问题描述

我正在学习从头开始为iOS开发应用程序。然后,我选择SwiftUI制作了一个应用程序,该应用程序可以获取用户的位置,对用户所在的城市进行地理编码,并获取所获得的信息,并通过API显示属于该城市的商品列表。

因此,我一方面学习了如何获取位置,另一方面又学习了如何显示列表。现在我的问题是w 当您运行.onAppear(perform:loadData)以显示我的列表时,“城市”结果仍然为空。显然,在尝试显示城市列表后,便获得了城市的价值。

这两种算法我都必须获取位置,而我必须要显示列表的算法分别工作。

所以我的代码是:

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()
    }
}

更新: LocationManager类

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()
    }
}

解决方法

就像您的代码一样,只需在收到的地标上加载数据,例如

        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()
            }
        }

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...