我正在尝试CLLocationManagerDelegate
通过协议扩展来实现协议要求,但位置管理器在协议扩展中看不到它并且失败了。但是,它在移入类时使用相同的代码。
这就是我正在做的事情:
class ViewController: UIViewController, MyLocationProtocol {
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers
locationManager.distanceFilter = 1000.0
locationManager.delegate = self
// Below crashes when implementation in protocol extension
locationManager.requestLocation()
}
}
protocol MyLocationProtocol: CLLocationManagerDelegate {
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
func locationManager(manager: CLLocationManager, didFailWithError error: NSError)
}
extension MyLocationProtocol /*where Self: UIViewControll*/ { // Tried using where clause but still no go :(
// Not being triggered by CLLocationManagerDelegate! :(
// Move to ViewController class and error goes away
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("MyLocationProtocol: locationManager: didUpdateLocations")
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("MyLocationProtocol: locationManager: didFailWithError")
}
}
请注意,extension MyLocationProtocol
我将didUpdateLocations
anddidFailWithError
实现放在那里。他们从来没有被触发并且实际上崩溃说:'Delegate must respond to locationManager:didUpdateLocations:'
。如果我将相同的didUpdateLocations
代码didFailWithError
移动到ViewController
,一切都会按预期工作。
关于为什么这不能通过协议扩展工作,我有什么遗漏吗?该类被识别为符合CLLocationManagerDelegate
,否则它将失败locationManager.delegate = self
。关于如何进行这项工作的任何想法或某处是否存在错误?