I have a Problem in my swift file.
Im trying to follow a tutorial on Youtube and he doesn’t get the error.
Here is the code:
class ViewController: UIViewController, CLLocationManagerDelegate {
private let locationManager = CLLocationManager()
private var currentLocation: CLLocationCoordinate2D?
@IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
configerLocationServices()
}
private func configerLocationServices() {
locationManager.delegate = self
let status = CLLocationManager.authorizationStatus()
if status == .notDetermined {
locationManager.requestWhenInUseAuthorization()
} else if status == .authorizedAlways || status == .authorizedWhenInUse {
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
}
extension ViewController: CLLocationManagerDelegate { //Error: Declaration is only valid at file scope
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("Did get latest Lcation")
}
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
print("The Status changed")
}
}
}
I don’t know what im doing wrong, has anyone a solution?
Thank you in advance.
2
Answers
Remove
CLLocationManagerDelegate
declaration inclass ViewController: UIViewController, CLLocationManagerDelegate
line. Also, make sure that you set all pairs of curly braces correctly, I mean open and close in proper placesThats because you have declared an extension inside your class. Move it outside the class and compiler will stop complaining
You have clearly confirmed to
CLLocationManagerDelegate
in yourViewController
extension so you dont need to confirm it in class declaration (this will result in compiler giving you a warning that duplicate confirmation to protocol) so changeclass ViewController: UIViewController, CLLocationManagerDelegate
toclass ViewController: UIViewController