1

I am programming a watch app based on some functionality of my iPhone app. On the phone, everything is working as intended, but on the watch app, I am getting location data too late. However, I can't figure out what is the correct way of doing it.

My working ContentView looks like this:

struct ContentView: View {

    @ObservedObject var locationManager = LocationManager()
    @ObservedObject var sunTimeData: SunTimeData

     var body: some View {
        VStack {
            OverView().environmentObject(sunTimeData)
        }.onAppear {
            self.setLocation()
         }
    }

    private func setLocation() {
        sunTimeData.latitude = locationManager.location?.latitude ?? 0
        sunTimeData.longitude = locationManager.location?.longitude ?? 0

        LocationManager.retreiveCityName(latitude: sunTimeData.latitude, longitude: sunTimeData.longitude) { (city) in
            self.sunTimeData.cityName = city ?? "Not found"
        }

    }

}

This is working fine and passing my location data to the environment object where I can use it in several views.

The Watch app is structured the same way, however, it doesn't obtain location info and just passes 0. If I call the locationManager INSIDE a view (inside a Text() for example), it will work, but as I use this on many different places, I would rather like to pass it to my environment object and go from there.

I tried adding variables above the body, but they are also still 0 at the time of calling. The locationManager starts to update just after rendering the view, it seems.

    var latitude: Double  {
        return locationManager.location?.latitude ?? 0
    }

    var longitude: Double {
        return locationManager.location?.longitude ?? 0
    }

I am using the HostingController.swift to have a paginated navigation (swipe between views) and the second page is having the correct location data.

class HostingController: WKHostingController<AnyView> {
    override var body: AnyView {
        return AnyView(TestView().environmentObject(SunTimeData()))
    }
}

class NewHostingController: WKHostingController<AnyView> {
    override var body: AnyView {
        return AnyView(ListView().environmentObject(SunTimeData()))
    }
}

Do I probably have to pass the locationManager to the views, too? Where is my mistake? Could anybody please guide me the right way to do this? Thank you.

wildfang
  • 315
  • 4
  • 9

0 Answers0