0

I have a function that takes my coordnaties that are stored inside of my Firebase Storage, and turns them into MKPointAnnotations For Some Reason I keep on getting the error Type '()' cannot conform to 'View'

Here is my code for the function:


import SwiftUI
import MapKit
import CoreLocationUI
import Firebase
import FirebaseFirestore

struct Marker: Identifiable {
    let id = UUID()
    var coordinate : CLLocationCoordinate2D
}

struct MapView: View {
    
    @StateObject private var viewModel = ContentViewModel()
    
    //For GeoCoder
    let geocoder = CLGeocoder()
    @State private var result = "result of lat & long"
    @State private var lat = 0.0
    @State private var long = 0.0
    @State private var country = "country name"
    @State private var state = "state name"
    @State private var zip = "zip code"
    
    //For Map Annotations
    @State var address = ""
    @State var realLat = 0.00
    @State var realLong = 0.00
    @State var email = ""
    
    //For TopBar
    @State var goToAddress = ""
    @State var filters = false
    
    var body: some View {
        
        let markers = [
            Marker(coordinate: CLLocationCoordinate2D(latitude: realLat, longitude: realLong))
        ]
        
        NavigationView {
            VStack {
                ZStack (alignment: .bottom) {
                    LocationButton(.currentLocation) {
                        viewModel.requestAllowOnceLocationPermission()
                    }
                    .foregroundColor(.white)
                    .cornerRadius(8)
                    .labelStyle(.iconOnly)
                    .symbolVariant(.fill)
                    .tint(.pink)
                    .padding(.bottom)
                    .padding(.trailing, 300)
                    
                    getAnnotations { (annotations) in
                        if let annotations = annotations {
                            Map(coordinateRegion: $viewModel.region, showsUserLocation: true, annotationItems: MKPointAnnotation) { annotations in
                                MapAnnotation(coordinate: annotations.coordinate) {
                                    Circle()
                                }
                            }
                            .ignoresSafeArea()
                            .tint(.pink)
                        } else {
                            print("There has been an error with the annotations")
                        }
                    }
                }
            }
        }
    }
    
    func getAnnotations(completion: @escaping (_ annotations: [MKPointAnnotation]?) -> Void) {
        let db = Firestore.firestore()
        
        db.collection("annotations").addSnapshotListener { (querySnapshot, err) in
            guard let snapshot = querySnapshot else {
                if let err = err {
                    print(err)
                }
                completion(nil) // return nil if error
                return
            }
            guard !snapshot.isEmpty else {
                completion([]) // return empty if no documents
                return
            }
            var annotations = [MKPointAnnotation]()
            
            for doc in snapshot.documents {
                if let lat = doc.get("lat") as? String,
                   let lon = doc.get("long") as? String,
                   let latitude =  Double(lat),
                   let longitude = Double(lon) {
                    let coord = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
                    let annotation = MKPointAnnotation()
                    annotation.coordinate = coord
                    annotations.append(annotation)
                }
            }
            completion(annotations) // return array
        }
    }
    
    func goToTypedAddress() {
        geocoder.geocodeAddressString(goToAddress, completionHandler: {(placemarks, error) -> Void in
            if((error) != nil){
                print("Error", error ?? "")
            }
            if let placemark = placemarks?.first {
                let coordinates:CLLocationCoordinate2D = placemark.location!.coordinate
                print("Lat: \(coordinates.latitude) -- Long: \(coordinates.longitude)")
                //added code
                result = "Lat: \(coordinates.latitude) -- Long: \(coordinates.longitude)"
                lat = coordinates.latitude
                long = coordinates.longitude
            }
        })
        print("\(lat)")
        print("\(long)")
    }
}
struct MapView_Previews: PreviewProvider {
    static var previews: some View {
        MapView()
    }
}

struct Item: Identifiable {
    let id = UUID()
    let text: String
}


//LocationButton
final class ContentViewModel: NSObject, ObservableObject, CLLocationManagerDelegate  {
    @Published var region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 40, longitude: 120), span: MKCoordinateSpan(latitudeDelta: 100, longitudeDelta: 100))
    
    let locationManager = CLLocationManager()
    
    override init() {
        super.init()
        locationManager.delegate = self
    }
    
    func requestAllowOnceLocationPermission() {
        locationManager.requestLocation()
    }
    
    func locationManager( _ _manager:CLLocationManager, didUpdateLocations locations: [CLLocation]){
        guard let latestLocation = locations.first else {
            // show an error
            return
        }
        DispatchQueue.main.async{
            self.region = MKCoordinateRegion(
                center: latestLocation.coordinate,
                span:MKCoordinateSpan(latitudeDelta:0.05, longitudeDelta:0.05))
        }
    }
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print(error.localizedDescription)
    }
}

The updated error is on line 50 now. Might be because of all of the new functions that I have. Also is the firebase function correct? I would like to make sure that it correct too.

  • What line of code causes the error? – Magnas Aug 09 '22 at 06:16
  • It isn't the code in here, but the Zstack surrounding it. –  Aug 09 '22 at 15:53
  • You need to show all relevant code. – Magnas Aug 09 '22 at 18:31
  • I updated all the code to show it. –  Aug 10 '22 at 14:20
  • I copied and pasted your code and there was an extra `}`. When this was removed, the `Type '()' cannot conform to 'View'` error went away. Your code is poorly structured. You shouldn't have model logic inside your stacks. – Magnas Aug 10 '22 at 16:01
  • Where was the `}` that you removed? –  Aug 11 '22 at 15:49
  • I think it was the very last one in the code you showed. – Magnas Aug 11 '22 at 16:41
  • I updated the code snippet, the error is now on line 50. –  Aug 11 '22 at 18:58
  • 1
    Please don't make us count to line 50. Tell us which line that is please! The code isn't well formatted so it's hard to tell which lines go with what but `goToTypedAddress` had a call `geocoder.geocodeAddressString` with a completion handler/closure followed by two `print` statements. I don't see where the handler is called but there's a good chance those print statements will execute before the code in the closure. – Jay Aug 12 '22 at 19:43
  • I am so sorry, I completely forgot that SO doesn't show lines. The error was in the first ZStack on the line of `ZStack (alignment: .bottom) {` I've tried removing the `}` at the bottom to see if anything works. The `goToTypedAddress` isn't the problem even after I removed the 2 print statements. –  Aug 13 '22 at 00:39
  • I found out that if you comment out the `getAnnotatoins { (annotations) in` the error goes away. Im not exactly sure what I did wrong there, because there is no error here during those lines –  Aug 13 '22 at 00:45
  • I copy and pasted your code and am not seeing the same issue. Perhaps the error lies elsewhere. How about commenting out ALL of that code and see if your app builds? – Jay Aug 15 '22 at 17:31
  • Yeah if you comment out all of the code, then the app builds, so there was an error somewhere there, I do have an updated question here: https://stackoverflow.com/questions/73356620/error-for-a-function-in-the-sorrounding-zstack-but-the-function-has-no-errors?noredirect=1#comment129551706_73356620 –  Aug 15 '22 at 18:43

0 Answers0