Получение широты и долготы пользователя - SwiftUI - PullRequest
0 голосов
/ 12 июля 2020

Я пытаюсь получить широту / долготу пользователя для использования в вызове API. Моя проблема в том, что, похоже, есть задержка в получении данных широты и долготы, и API в конечном итоге отправляет значения по умолчанию вместо фактических значений. Должен ли я пытаться получить широту / долготу в представлении root или есть способ заставить мою функцию ждать, пока не будут получены фактические значения? Ниже мой код для представления, в котором я работаю (не root)

struct ExploreView: View {
@ObservedObject var locationManager: LocationManager
@ObservedObject var fetcher: RestaurantFetcher


init() {
    let locationManager = LocationManager()
    self.locationManager = locationManager
    self.fetcher = RestaurantFetcher(locationManager: locationManager)
}

var body: some View {
    
    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(locationManager: LocationManager) {
    self.locationManager = locationManager
    load()
}

func load() {
    print("\(self.locationManager.userLatitude),\(self.locationManager.userLongitude)")
    print("user latitude above")
    //Returns default values of 0.0,0.0
    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")!
// Call to Yelp's API
    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 {
                print("\(self.locationManager.userLatitude),\(self.locationManager.userLongitude)")
                print("user latitude above")
                let decodedLists = try JSONDecoder().decode(BusinessesResponse.self, from: d)
                print("\(self.locationManager.userLatitude),\(self.locationManager.userLongitude)")
                print("User coords")
                // Returns actual location coordinates
                DispatchQueue.main.async {
                    self.businesses = decodedLists.restaurants
                }
            } else {
                print("No Data")
            }
        } catch {
            print ("Caught")
        }
    }.resume()
}
}
...