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
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.
When I want to capture the location of the GPS sensor, I just extend a UIViewController using the LocateViewController.
Just like that example below:
It works for me.
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: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.You’re going to have to reconsider your reason for wanting to make
getLocation
static, and find a different approach.