在 Swift 中使用带有静态函数的委托
Using delegate with a static function in Swift
这是我在我的应用程序中使用的功能,效果很好。
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
}
}
但我想将此函数更改为静态函数,就像
static func getLocation() { // some code }
但是我在这部分代码上遇到了错误
locationManager.delegate = self
无法将类型 'ResenhaEquideosMenuController.Type' 的值分配给类型 'CLLocationManagerDelegate?'
我该如何解决?
静态函数不依赖于它们所属类型的任何特定实例,因此在您执行操作时从内部引用 self
:
locationManager.delegate = self
没有任何意义。 self
表示为函数调用提供上下文的特定对象,静态函数不可用。
How can I fix that?
您将不得不重新考虑要使 getLocation
静态的原因,并找到不同的方法。
我没有找到使用具有静态函数的委托来解决我的 CCLocationManager 问题的方法 class。
因此,根据@DuncanC 的评论,我创建了一个新的 class,它扩展了一个名为 LocationViewController 的 UIViewController。
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)
}
}
当我想捕捉 GPS 传感器的位置时,我只是使用 LocateViewController 扩展了一个 UIViewController。
就像下面的例子:
class ResenhaEquideosMenuController: LocationViewController { ...code }
对我有用。
这是我在我的应用程序中使用的功能,效果很好。
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
}
}
但我想将此函数更改为静态函数,就像
static func getLocation() { // some code }
但是我在这部分代码上遇到了错误
locationManager.delegate = self
无法将类型 'ResenhaEquideosMenuController.Type' 的值分配给类型 'CLLocationManagerDelegate?'
我该如何解决?
静态函数不依赖于它们所属类型的任何特定实例,因此在您执行操作时从内部引用 self
:
locationManager.delegate = self
没有任何意义。 self
表示为函数调用提供上下文的特定对象,静态函数不可用。
How can I fix that?
您将不得不重新考虑要使 getLocation
静态的原因,并找到不同的方法。
我没有找到使用具有静态函数的委托来解决我的 CCLocationManager 问题的方法 class。
因此,根据@DuncanC 的评论,我创建了一个新的 class,它扩展了一个名为 LocationViewController 的 UIViewController。
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)
}
}
当我想捕捉 GPS 传感器的位置时,我只是使用 LocateViewController 扩展了一个 UIViewController。
就像下面的例子:
class ResenhaEquideosMenuController: LocationViewController { ...code }
对我有用。