skip to Main Content

This is a function that I use it in my app, it works perfectly.

class ResenhaEquideosMenuController: UIViewController, CLLocationManagerDelegate {

static let locationManager = CLLocationManager()

func getLocation() {
    let status = CLLocationManager.authorizationStatus()
    
    switch status {
        case .notDetermined:
                locationManager.requestWhenInUseAuthorization()
                return
            
        case .denied, .restricted:
            let alert = UIAlertController(title: "Serviços de localização desativados", message: "Por favor, ative os Serviços de Localização nas Configurações do seu dispositivo", preferredStyle: .alert)
            let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
            alert.addAction(okAction)
            
            present(alert, animated: true, completion: nil)
            return
        case .authorizedAlways, .authorizedWhenInUse:
            break
    }
    
    locationManager.delegate = self
    locationManager.startUpdatingLocation() // função didUpdateLocations controla quando GPS capta atualização do Sensor
}
}

But I wanna change this function to a static function just like

static func getLocation() { // some code }

But I got en error on this part of the code

locationManager.delegate = self

Cannot assign value of type ‘ResenhaEquideosMenuController.Type’ to type ‘CLLocationManagerDelegate?’

How can I fix that?

2

Answers


  1. Chosen as BEST ANSWER

    I didn't find a way to use the delegate with a static function to fix my problem with the CCLocationManager class.

    So, based in @DuncanC comment, I create a new class that extends a UIViewController called LocationViewController.

    import Foundation
    import CoreLocation
    
    class LocationViewController: UIViewController, CLLocationManagerDelegate {
    
    let locationManager = CLLocationManager()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        print("___ LocationViewController viewDidLoad")
        getLocation()
    }
    
    func getLocation() {
        let status = CLLocationManager.authorizationStatus()
        
        switch status {
            case .notDetermined:
                    locationManager.requestWhenInUseAuthorization()
                    return
                
            case .denied, .restricted:
                let alert = UIAlertController(title: "Serviçoõs de localização desativados", message: "Por favor, ative os Serviços de Localização nas Configurações do seu dispositivo", preferredStyle: .alert)
                let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
                alert.addAction(okAction)
                
                present(alert, animated: true, completion: nil)
                return
            case .authorizedAlways, .authorizedWhenInUse:
                break
            @unknown default:
                print("erro desconhecido")
        }
        
        locationManager.delegate = self
        locationManager.startUpdatingLocation() // função didUpdateLocations controla quando GPS capta atualização do Sensor
    }
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let currentLocation = locations.last {
            manager.distanceFilter = 50 // distance changes you want to be informed about (in meters)
            manager.desiredAccuracy = 10 // biggest approximation you tolerate (in meters)
            //manager.activityType = .automotiveNavigation // .automotiveNavigation will stop the updates when the device is not moving
            saveLocationPosition(currentLocation)
        }
    }
    
    fileprivate func saveLocationPosition(_ currentLocation: CLLocation) {
        UserDefaults.standard.set(currentLocation.coordinate.latitude, forKey: RESconstantes.LATITUDE_USER)
        UserDefaults.standard.set(currentLocation.coordinate.longitude, forKey: RESconstantes.LONGITUDE_USER)
    }
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("locationManager error")
        print(error)
    }
    
    }
    

    When I want to capture the location of the GPS sensor, I just extend a UIViewController using the LocateViewController.

    Just like that example below:

    class ResenhaEquideosMenuController: LocationViewController { ...code }
    

    It works for me.


  2. Static functions don’t depend on any particular instance of the type that they belong to, so referencing self from inside one as you’re doing:

    locationManager.delegate = self
    

    doesn’t make any sense. self represents a particular object that provides context for the function call, and that’s not available to a static function.

    How can I fix that?

    You’re going to have to reconsider your reason for wanting to make getLocation static, and find a different approach.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search