Я использую этот класс, чтобы получить местоположение и отправить его с делегатом другому контроллеру представления, но делегат возвращает nil при вызове.
мой класс:
protocol LocationUpdateProtocol {
func locationDidUpdateToLocation(location : CLLocation)
}
/// Notification on update of location. UserInfo contains CLLocation for key "location"
let kLocationDidChangeNotification = "LocationDidChangeNotification"
class LocationServiceHelper:NSObject,CLLocationManagerDelegate {
static let sharedManager = LocationServiceHelper()
private let locationManager = CLLocationManager()
var currentLocation:CLLocation?
weak var delegate :LocationUpdateProtocol?
private override init() {
super.init()
self.locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = kCLLocationAccuracyHundredMeters
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
// MARK: CLLocationManagerDelegate
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let delegate = self.delegate else {
return
}
currentLocation = locations.first
let userInfo:NSDictionary = ["location":currentLocation!]
delegate.locationDidUpdateToLocation(location: currentLocation!)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: kLocationDidChangeNotification), object: self, userInfo: userInfo as? [AnyHashable : Any])
}
}
Я вызвал делегата в другом классе ниже:
var locationServiceReference = LocationServiceHelper.sharedManager
override func viewDidLoad() {
super.viewDidLoad()
fillFields()
locationServiceReference.delegate = self
self.mapView.showsUserLocation = true
}
func locationDidUpdateToLocation(location: CLLocation) {
// print(location)
// let myLocation = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
let myLocationForTesting = CLLocationCoordinate2D(latitude: 33.410165, longitude: 35.480060)
myLocation = location
let region = MKCoordinateRegion(center: myLocationForTesting, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
self.mapView.setRegion(region, animated: true)
}
в местоположении обновления, делегат возвращает ноль, есть идеи, что происходит? функция не была вызвана, так как делегат возвращает ноль.