ios - 如何等待另一个值被分配来运行.onAppear?

标签 ios swift swiftui cllocationmanager

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

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

获取位置的算法和显示列表的算法都是分开工作的。

所以我的代码是:

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

关于ios - 如何等待另一个值被分配来运行.onAppear?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63964251/

相关文章:

ios - 允许 SwiftUI 导入所有联系人并删除特定联系人

ios - AFNetworking 从响应中删除字符

ios - 在 applicationWillTerminate 中发出套接字事件

swift - 发生错误时调用 completionHandler

swift - 无法获取新密码以生成强密码和自动填充

SwiftUI 未知属性 'Observable Object'

swift - 在 SwiftUI (Xcode 12) 中折叠侧边栏

ios - tabBarController.selectedViewController 的默认值?

ios - SecItemAdd() 返回 errSecInteractionNotAllowed (-25308)

javascript - 列表项不会因打开辅助功能而改变高度以响应大文本