Ios 如何等待另一个值被分配到run.onAppear?
我正在学习从头开始为iOS开发应用程序。我选择了SwiftUI来制作一个应用程序,它可以获取用户的位置,通过地理编码获取他所在的城市,并通过获取的信息,从API中显示属于该城市的项目列表 因此,我一方面学会了如何获取位置,另一方面学会了如何显示列表。我现在的问题是,当您运行.onAppear(perform:loadData)显示我的列表时,“city”结果仍然是空的。显然,城市的值是在我尝试显示城市列表后获得的 我必须得到位置的算法和我必须单独显示列表的算法都有效 所以我的代码是:Ios 如何等待另一个值被分配到run.onAppear?,ios,swift,swiftui,cllocationmanager,Ios,Swift,Swiftui,Cllocationmanager,我正在学习从头开始为iOS开发应用程序。我选择了SwiftUI来制作一个应用程序,它可以获取用户的位置,通过地理编码获取他所在的城市,并通过获取的信息,从API中显示属于该城市的项目列表 因此,我一方面学会了如何获取位置,另一方面学会了如何显示列表。我现在的问题是,当您运行.onAppear(perform:loadData)显示我的列表时,“city”结果仍然是空的。显然,城市的值是在我尝试显示城市列表后获得的 我必须得到位置的算法和我必须单独显示列表的算法都有效 所以我的代码是: impor
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()
}
}
<代码>导入基础
导入核心定位
进口联合收割机
类位置管理器:NSObject,observeObject{
私有let locationManager=CLLocationManager()
私有let geocoder=CLGeocoder()
let objectWillChange=PassthroughSubject()
@已发布变量状态:CLAuthorizationStatus{
willSet{objectWillChange.send()}
}
@发布的变量位置:CLLocation{
willSet{objectWillChange.send()}
}
重写init(){
super.init()
self.locationManager.delegate=self
self.locationManager.desiredAccuracy=KCallocationAccuracyBest
self.locationManager.requestWhenUseAuthorization()
self.locationManager.startUpdatingLocation()
}
@已发布变量placemark:CLPlacemark{
willSet{objectWillChange.send()}
}
专用func地理代码(){
guard let location=self.location else{return}
geocoder.reverseGeocodeLocation(位置,completionHandler:{(位置,错误)在
如果错误==nil{
self.placemark=位置?[0]
}否则{
self.placemark=nil
}
})
}
}
扩展位置管理器:CLLocationManagerDelegate{
func locationManager(\ manager:CLLocationManager,didChangeAuthorization状态:CLAuthorizationStatus){
self.status=状态
}
func locationManager(manager:CLLocationManager,didUpdateLocations位置:[CLLocation]){
guard let location=locations.last else{return}
self.location=位置
self.geocode()
}
}
正如您的代码一样,只需在收到的placemark上加载数据,如
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()
}
}
没有完整的代码很难回答这个问题。问题是,当您初始化城市时,LocationManager尚未设置。我会尝试在LocationManager中将city设置为一个变量,并在初始化期间进行设置,无论何时需要访问它,都可以调用lm。city@purebreadd我认为没有必要,但请检查我添加LocationManager类的更新。在这个类的init()中,您要在其中添加lm.city吗?你能告诉我你将如何做,以及你以后在HomeScreenView中如何使用它吗?