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.
Thats because you have declared an extension inside your class. Move it outside the class and compiler will stop complaining
class ViewController: UIViewController {
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 {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("Did get latest Lcation")
}
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
print("The Status changed")
}
}
You have clearly confirmed to CLLocationManagerDelegate
in your ViewController
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 change class ViewController: UIViewController, CLLocationManagerDelegate
to class ViewController: UIViewController