Is there a way to display a users current address in the textfield on appear of the page?

46 Views Asked by At

I am newer to Swift and I have been trying to figure out how to get the user's current location to appear in the textField where "Enter Address: " is on the appear of the app page. This is the code that I have currently, but can't seem to get the location to update into the textfield. I was able to get the user current location displayed but I just can't seem to figure out how to get it into the textField on appear.

import SwiftUI
import CoreLocation
import Combine

struct LocationView: View {
    
    @ObservedObject var location = TextView()
    @State var latitude: Double = 0
    @State var longitude: Double = 0
    
    @State private var address: String = ""
    @State private var coordinates: CLLocationCoordinate2D?
    
    @StateObject private var locationManager = LocationManager()
    
    @State var loading = false
    
    @State var errorMessage: String = ""
    @State var errors = ErrorType(state: "", message: "", imagename: "")
    
    var body: some View {
        List {
            Section("Location") {
                HStack {
                    Text("Enter Address: ").bold()
                    TextField("", text: $location.updatedText)
                        .multilineTextAlignment(.trailing)
                    Spacer()
                }
                
                if errorMessage.isEmpty {
                    VStack(alignment: .leading) {
                        HorizontalView(title: "Latitude", value: String(latitude))
                        HorizontalView(title: "Longitude", value: String(longitude))
                    }
                } else {
                    VStack(alignment: .leading) {
                        Text("Error while looking up location")
                        Text(errorMessage)
                            .font(.caption)
                            .foregroundStyle(.secondary)
                    }
                }
            }
        }
        
        .onReceive(location.$text) { value in
            getLocation(addressString: value) { coordinate, error in
                if let error = error {
                    errorMessage = error.localizedDescription
                    longitude = 0
                    latitude = 0
                } else {
                    errorMessage = ""
                    latitude = coordinate.latitude
                    longitude = coordinate.longitude
                }
            }
        }
        
        .onAppear {
            location.updatedText = "1 Apple Park Way Cupertino, CA"
        }
    }
    
    func getLocation(
        addressString: String,
        completionHandler: @escaping(CLLocationCoordinate2D, NSError?) -> Void
    ) {
        let geocoder = CLGeocoder()
        geocoder.geocodeAddressString(addressString) { placemarks, error in
            if error == nil {
                if let placemark = placemarks?[0] {
                    let location = placemark.location!

                    completionHandler(location.coordinate, nil)
                    return
                }
            }

            completionHandler(kCLLocationCoordinate2DInvalid, error as NSError?)
        }
    }
    
}

struct HorizontalView: View {
    let title: String
    let value: String

    var body: some View {
        HStack {
            Text(title)
                .bold()
            Spacer()
            Text(value)
                .multilineTextAlignment(.trailing)
        }
    }
}

struct ErrorType {
    var state: String
    var message: String?
    var imagename: String
}

final class TextView: ObservableObject {
    private var disposeBag = Set<AnyCancellable>()

    @Published var updatedText: String = ""
    @Published var text: String = ""

    init() {
        self.TextChanges()
    }

    private func TextChanges() {
        $updatedText
            .debounce(for: 1, scheduler: RunLoop.main)
            .sink {
                self.text = $0
            }
            .store(in: &disposeBag)
    }
}

struct GridSignalView_Preview: PreviewProvider {
    static var previews: some View {
        LocationView()
    }
}
0

There are 0 best solutions below