В некоторых частях моего приложения мой список SwiftUI не отображает правильные данные - PullRequest
0 голосов
/ 09 апреля 2020

В моем приложении swiftUI я должен отображать несколько ресторанов рядом с пользователем. когда я нажимаю кнопку поиска в моем CategoryView, он не работает, но когда я нажимаю кнопку, содержащую ту же строку кода в моем RestrauntView, он работает отлично. в моем CategoryView строка -

self.RestrauntListVM.loadBusinesses(lat: self.RestrauntListVM.currentLocation.coordinate.latitude, long: self.RestrauntListVM.currentLocation.coordinate.longitude, theTerm: self.foodCategory)

, а в моем RestrauntView -

self.restrauntListViewModels.loadBusinesses(lat: self.restrauntListViewModels.currentLocation.coordinate.latitude, long: self.restrauntListViewModels.currentLocation.coordinate.longitude, theTerm: self.foodCategory)

Может кто-нибудь помочь мне разобраться? Вот мой код:

RestrauntListViewModel.Swift:

    import SwiftUI
    import MapKit
    import CoreLocation
    import Moya
    import Alamofire
    import CoreData

    class RestrauntListViewModel: ObservableObject {
    @Published var Model = [RestrauntListModel(name: "error", imageURL: URL(string: "error")!, distance: 3, id: "3", rating: 3)]



    let locationService = LocationService()
    var currentLocation = CLLocation()

    init () {
        locationService.didChangeStatus = { [weak self] success in
            if success {
                self?.locationService.getLocation()
            }
        }
        locationService.newLocation = { [weak self] result in
            switch result {
            case .success(let location):
                print("got new location \(location)")
            case .failure(let error):
                assertionFailure("Error getting the users location \(error)")
            }
        }
        locationService.setup()
    }
    func loadBusinesses (lat: Double, long: Double, theTerm: String) {
                   let service = MoyaProvider<YelpService.BusinessProvider>()
                   let jsonDecoder = JSONDecoder()
                   if CLLocationManager.locationServicesEnabled() {

                    switch CLLocationManager.authorizationStatus() {
                           case .notDetermined, .restricted, .denied:
                               print("No access inside function to the location")
                           case .authorizedAlways, .authorizedWhenInUse:
                               print("Access in the function to the location")

                               service.request(.search(lat: lat, long: long, term: theTerm)) { (result) in
                                               switch result{
                                               case.success(let response):
                                                   print("yaya")
                                                   let root = try? jsonDecoder.decode(Root.self, from: response.data)
                                                   let dataSource = DataSource()
                                                   dataSource.arrayOfImages.removeAll()
                                                   self.Model = root?.businesses.compactMap(RestrauntListModel.init) ?? [RestrauntListModel(name: "viewModel is nil in the load busissnes function", imageURL: URL(string: "error")!, distance: 3, id: "error", rating: 3)]
                                                   print("this is model \(self.Model)")
                                               case .failure(let error):
                                                   print("Error: \(error)")
                                               }
                           }
                           @unknown default:
                           break
                       }
                       } else {
                           print("Location services are not enabled")
                   }

               }
    }

CategoryView.Swift:

    import SwiftUI

    struct CategoryView: View {
    @ObservedObject var RestrauntListVM = RestrauntListViewModel()
    @Binding var foodCategory: String
    var body: some View {
        NavigationView {
            VStack {

                    Text("You Got ")
                        .font(.custom("Source Sans Pro", size: 38)) + Text(foodCategory)
                        .font(.custom("Source Sans Pro", size: 35))
                        .foregroundColor(.red)

                Spacer()
                Image("Globe")
                Spacer()


                    Text("Want To Find ")
                        .font(.custom("Source Sans Pro", size: 30)) + Text(foodCategory)
                        .font(.custom("Source Sans Pro", size: 30))
                        .foregroundColor(.red) + Text( "Around You?")
                        .font(.custom("Source Sans Pro", size: 30))

                Spacer()
                NavigationLink(destination: RestrauntView(foodCategory: foodCategory)) {
                    Image("Find Button")
                        .renderingMode(.original)

                }.simultaneousGesture(TapGesture().onEnded{
                    self.RestrauntListVM.loadBusinesses(lat: self.RestrauntListVM.currentLocation.coordinate.latitude, long: self.RestrauntListVM.currentLocation.coordinate.longitude, theTerm: self.foodCategory)
                })
                Spacer()

            }
            .padding()
        }
    }
    }

RestrauntView.Swift

    import SwiftUI
    struct RestrauntView: View {

    @ObservedObject var restrauntListViewModels = RestrauntListViewModel()
    var foodCategory: String
    var body: some View {


        List(restrauntListViewModels.Model) { viewModel in
            ListCellView(viewModel: viewModel)
        }
    .navigationBarTitle("Restraunts")
        .navigationBarItems(trailing: Button(action: {
            self.restrauntListViewModels.loadBusinesses(lat: self.restrauntListViewModels.currentLocation.coordinate.latitude, long: self.restrauntListViewModels.currentLocation.coordinate.longitude, theTerm: self.foodCategory)
        }, label: {
            Text("Refresh")

        }))


    }

    init(foodCategory: String) {
        self.foodCategory = foodCategory
    }
    }

    struct RestrauntView_Previews: PreviewProvider {
    static var previews: some View {
        RestrauntView(foodCategory: "AMerican")
    }
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...