Home > Mobile >  SwiftUI error - "Delegate must respond to locationManager:didFailWithError:"
SwiftUI error - "Delegate must respond to locationManager:didFailWithError:"

Time:03-12

I'm trying to implement MapKit and CoreLocation in SwiftUI to fetch user locations in my app, check permissions, handle errors etc.. but I'm getting this error when I run the simulator and grant location permission.

Not sure what I'm doing wrong. Any help is appreciated

Here's a screenshot with where the error message shows

And here's my code which I presume is missing something that's causing the error:

import SwiftUI
import MapKit
import CoreLocation

// All Map data goes here

class MapViewModel: NSObject,ObservableObject, CLLocationManagerDelegate{
    
    @Published var mapView = MKMapView()
    
    // Region...
    @Published var region : MKCoordinateRegion!
    // Based on location it will set up...
    
    // Alert...
    @Published var permissionDenied = false
    
    // Map Type...
    @Published var mapType : MKMapType = .standard
    
    func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
        
        // Checking permissions...
        
        switch manager.authorizationStatus {
        case .denied:
            // Alert...
            permissionDenied.toggle()
        case .notDetermined:
            // Requesting...
            manager.requestWhenInUseAuthorization()
        case .authorizedWhenInUse:
            // If permission given...
            manager.requestLocation()
        default:
            ()
        }
    }
    
func locationManager(_manager: CLLocationManager, didFailWithError error: Error) {
        
        // Error...
        print(error.localizedDescription)
    }
    
    // Getting user Region...
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations:
                         [CLLocation]) {
        
        guard let location = locations.last else {return}
        
        self.region = MKCoordinateRegion(center: location.coordinate, latitudinalMeters: 10000, longitudinalMeters: 10000)
        
        // Updating Map...
        self.mapView.setRegion(self.region, animated: true)
         
        // Smooth animation...
        self.mapView.setVisibleMapRect(self.mapView.visibleMapRect, animated: true)
    }
    
}

CodePudding user response:

func locationManager(_manager: CLLocationManager,

should be

func locationManager(_ manager: CLLocationManager,

CodePudding user response:

as @Shadowrun showed you (_manager: is a parameter which is named manager but ( manager: means to hide the parameter name.

  • Related