【发布时间】:2016-02-20 15:08:55
【问题描述】:
我正在尝试通过协议扩展实现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 和didFailWithError 实现放在那里。他们永远不会触发并实际上崩溃说:'Delegate must respond to locationManager:didUpdateLocations:'。如果我将相同的didUpdateLocations 和didFailWithError 代码移动到ViewController,一切都会按预期进行。
关于为什么这不能通过协议扩展工作,我有什么遗漏吗?该类被识别为符合CLLocationManagerDelegate,否则它将在locationManager.delegate = self 处失败。关于如何使这项工作的任何想法或某处是否存在错误?
【问题讨论】:
-
requestLocation() 函数来自哪里?
标签: ios swift swift2 cllocationmanager protocol-extension