-1

When trying to find the location of a user, I use CLLocationManager. Where I have this line:

locationManager.delegate = self

It returns this error:

Value of type '(CLLocationManager, [CLLocation]) -> ()' has no member ‘delegate'

Here is the code:

import CoreLocation
import UIKit
import SwiftUI
import Mapbox

class MapsViewController: UIViewController, MGLMapViewDelegate {
    var locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.locationManager.requestWhenInUseAuthorization()
        if CLLocationManager.locationServicesEnabled(){
            locationManager.delegate = self //this is where I get the error said above
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.startUpdatingLocation()
        }
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]){
        let locValue:CLLocationCoordinate2D = manager.location!.coordinate
        print("locations = \(locValue.latitude) \(locValue.longitude)")
    }
}

I have tried the error on stackoverflow and solving it myself, but nothing has helped so far. It might be a problem with the new version of Swift & Xcode (as I am following this tutorial)

I add Privacy - Location When In Use Usage Description and Privacy - Location Always and When In Use Usage Description in Info.plist for anyone wondering.

Rob
  • 415,655
  • 72
  • 787
  • 1,044
Darrow Hartman
  • 4,142
  • 2
  • 17
  • 36

2 Answers2

3

Add CLLocationManagerDelegate

class MapsViewController: UIViewController,MGLMapViewDelegate,CLLocationManagerDelegate{
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
1

Sh_Khan’s answer is correct, but I might suggest pulling the conformance to CLLocationManagerDelegate protocol into its own extension:

extension MapsViewController: CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]){
        guard let coordinate = locations.last?.coordinate else { return }

        print("locations = \(coordinate.latitude) \(coordinate.longitude)")
    }
}

Separating protocol conformance from the base class implementation keeps code nicely organized and enables code folding (e.g. command+option+). For a view controller this small it doesn’t matter, but as the code for this view controller grows, it’s really convenient to use extensions to organize it.

See Adding Protocol Conformance with an Extension in The Swift Programming Language.

Rob
  • 415,655
  • 72
  • 787
  • 1,044