swift - 实现定位协议
问题描述
我喜欢面向协议编程的概念,我正在尝试通过协议扩展快速开始编写协议。
我正在尝试使用协议扩展来获取设备位置。
但是,我在创建它时遇到了以下问题:
import Foundation
import CoreLocation
protocol Locator:CLLocationManagerDelegate {
var locationManager:CLLocationManager!
{ get set }
var locationHandler: ((CLLocation)->())?
{ get set }
func getLocation(completionHandler:@escaping (CLLocation)->())
}
extension Locator {
private var _locationManager:CLLocationManager {
get {return self.locationManager} set {self.locationManager = newValue}
}
private var _locationHandler:((CLLocation)->())? {
get {return self.locationHandler} set {self.locationHandler = newValue}
}
func getLocation(completionHandler:@escaping (CLLocation)->()) {
self.locationManager = CLLocationManager()
self.locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers
let status = CLLocationManager.authorizationStatus()
switch status {
case .notDetermined:
self.locationManager.requestAlwaysAuthorization()
return
case .denied, .restricted:
return
case .authorizedAlways, .authorizedWhenInUse:
self.locationManager.startUpdatingLocation()
@unknown default:
break
}
self.locationHandler = completionHandler
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .authorizedWhenInUse || status == .authorizedAlways {
self.locationManager.startUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("Hey this is a location")
if let currentLocation = locations.last {
self._locationHandler?(currentLocation)
}
}
}
但是,完成处理程序无法正常工作。
我的问题是什么,我该如何继续在协议概念中创建它。
解决方案
推荐阅读
- apache - Forbidden You don't have permission to access this resource 保存带有嵌入式 pdf 的网页时出现错误
- sql - 如何使这个 2 步查询解决方案更好
- android - Ionic cordova build android –prod –release only builds a debug apk (app-debug.apk)
- laravel - 登录后 Laravel 电子邮件验证将用户重定向回验证 url
- aerospike - 使用 aerospike 操作命令创建记录
- parse-platform - 具有多个“或”的全文在解析服务器中引发错误
- swift - 在 swift 中使用委托时出错
- ios - 应用程序显示在 App Store Connect 的活动选项卡中,但无法发布
- javascript - 如何在基于函数的 ReactJS 组件中调用函数?
- c# - C# Spire.Pdf.PdfDocument 破坏 PDF 大小