Class SwiftUI-将用户位置信息从LocationManager传递到另一个类

Class SwiftUI-将用户位置信息从LocationManager传递到另一个类,class,swiftui,cllocationmanager,Class,Swiftui,Cllocationmanager,我试图将用户的lat/long从LocationManager传递到API调用。我能够在页面的主视图中成功地传递值,但是从我为API调用构建的RestaurantFetcher类中访问它会返回nil 我确信这是一件我不知道的简单事情,但是我如何能够获取该lat/long,以便将其插入RestaurantFetcher类中API的调用URL中呢 以下是查看代码: struct ExploreView: View { @ObservedObject var locationManager = Lo

我试图将用户的lat/long从LocationManager传递到API调用。我能够在页面的主视图中成功地传递值,但是从我为API调用构建的RestaurantFetcher类中访问它会返回nil

我确信这是一件我不知道的简单事情,但是我如何能够获取该lat/long,以便将其插入RestaurantFetcher类中API的调用URL中呢

以下是查看代码:

struct ExploreView: View {

@ObservedObject var locationManager = LocationManager()
@ObservedObject var fetcher = RestaurantFetcher()

var body: some View {
    
    return ScrollView(.vertical) {
        HStack {
            Text("Latitude: \(locationManager.userLatitude)")
              //Returns valid latitude
                .font(.title)
                .fontWeight(.bold)
            Spacer()
        }.padding(.horizontal)
        VStack {
            ForEach(fetcher.businesses) { restaurant in
                VStack (alignment: .leading) {
                    WebImage(url: URL(string: restaurant.image_url))
                        .resizable()
                        .indicator(.activity) // Activity Indicator
                        .transition(.fade(duration: 0.5)) // Fade Transition with duration
                        .scaledToFill()
                        .frame(width: 240, height: 300, alignment: .center)
                        
                        .clipped()
                        .cornerRadius(4)
                    
                    Text(restaurant.name)
                        .fontWeight(.bold)
                    HStack(spacing: 5.0) {
                        Text(restaurant.price ?? "No Pricing Info")
                            .font(.caption)
                        Text("·")
                        ForEach(restaurant.categories, id: \.self) { cat in
                            Text(cat.title)
                                .font(.caption)
                        }
                        Text("·")
                    }
                    HStack(spacing: 5.0) {
                        Image(systemName: "star.fill")
                            .font(.caption)
                        Text("\(restaurant.rating, specifier: "%.1f")")
                            .font(.caption)
                        Text("(\(restaurant.review_count))")
                            .font(.caption)
                        Spacer()
                    }
                    HStack {
                        Text(restaurant.location.city)
                    }
                }
            }.padding(.bottom)
            .padding(.horizontal, 20)
        }
    }
}
}

struct ExploreView_Previews: PreviewProvider {
static var previews: some View {
    ContentView()
}
}


public class RestaurantFetcher: ObservableObject {
    @Published var businesses = [RestaurantResponse]()
    @ObservedObject var locationManager = LocationManager()

init() {
    load()
}
func load() {
    print("\(locationManager.userLongitude),\(locationManager.userLatitude)")
    //Returns nil
    let apikey = "API-KEY"
    
    let url = URL(string: "https://api.yelp.com/v3/businesses/search?latitude=\(self.locationManager.userLatitude)&longitude=\(self.locationManager.userLongitude)&radius=40000")!
    var request = URLRequest(url: url)
    request.setValue("Bearer \(apikey)", forHTTPHeaderField: "Authorization")
    request.httpMethod = "GET"
    
    URLSession.shared.dataTask(with: request) { (data, response, error) in
        do {
            if let d = data {
                let decodedLists = try JSONDecoder().decode(BusinessesResponse.self, from: d)
                print("\(self.locationManager.userLongitude),\(self.locationManager.userLatitude)")
                DispatchQueue.main.async {
                    self.businesses = decodedLists.restaurants
                }
            } else {
                print("No Data")
            }
        } catch {
            print ("Caught")
        }
    }.resume()
}
}

您正在两个视图中创建
LocationManager
的新实例。这意味着您正在使用两个不同的实例:

struct ExploreView: View {
    @ObservedObject var locationManager = LocationManager()
    ...
}

struct RestaurantFetcher: View {
    @ObservedObject var locationManager = LocationManager()
    ...
}
因此,您在
ExploreView
中访问的
LocationManager
与您在
RestaurantFetcher
中访问的不同。这就是为什么
locationManager.userLatitude
返回不同的结果

您需要在两个视图中使用一个实例:

struct ExploreView: View {
    @ObservedObject var locationManager: LocationManager
    @ObservedObject var fetcher: RestaurantFetcher
    
    init() {
        let locationManager = LocationManager()
        self.locationManager = locationManager
        self.fetcher = RestaurantFetcher(locationManager: locationManager)
    }
    ...
}
公共类RestaurantFetcher:ObservableObject{
@已发布的var业务=[RestaurantResponse]()

@ObservedObject var locationManager:locationManager//fetcher的初始值设定项正在抛出一个错误“在初始化所有存储属性之前自行使用”@jasonTermain在哪一行?记住只在
RestaurantFetcher
中声明
locationManager
。行“fetcher=RestaurantFetcher”(locationManager:locationManager)“是的,我删除了重复声明。我复制并粘贴了上面的代码。@JasonTermain噢,谢谢,我的错。我更新了代码。
public class RestaurantFetcher: ObservableObject {
    @Published var businesses = [RestaurantResponse]()
    @ObservedObject var locationManager: LocationManager // <- declare only

    init(locationManager: LocationManager) {
        self.locationManager = locationManager
        load()
    }
    ...
}