class LocationManager: NSObject, CLLocationManagerDelegate {
private var onLocation: ((CLLocationCoordinate2D) -> Void)?
private let manager: CLLocationManager
override init() {
manager = CLLocationManager()
super.init()
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
manager.delegate = self
manager.startUpdatingLocation()
}
public func getLocation(_ onLocation: ((CLLocationCoordinate2D) -> Void)?) {
self.onLocation = onLocation
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print(#function, locations)
guard let currentCoordinate = manager.location?.coordinate else {return}
onLocation?(currentCoordinate)
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print(#function, error)
}
}
this code is not calling didUpdateLocation or didFailWithError. can anyone tell me what could be the problem here?
LocationManager().getLocation { coordinate in
print(#function, coordinate)
}
this is how i am calling it.
You need to retain the let manager = CLLocationManager() in your class as a property. Otherwise, it will be deallocated at the end of that function and hence none of its delegate methods will be called at all.
UPDATED
Another issue is the following code where you call getLocation. You need to retain LocationManager() in your client class otherwise the LocationManager will be deallocated at the end of that function.
private let locationManager = LocationManager()
locationManager.getLocation { coordinate in
print(#function, coordinate)
}
Related
So I am dealing with an issue where the LocationManager file that I have, and the didUpdateLocations function, is being called multiple times on application startup and I can't figure out what is causing it.
So I have the following LocationManager:
import Foundation
import CoreLocation
import MapKit
final class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate {
#Published var userLocation: CLLocation?
#Published var defaultRegion: MKCoordinateRegion?
#objc static let getInstance = LocationManager()
private let locationManager = CLLocationManager()
override init() {
super.init()
locationManager.delegate = self
log.info("\n 🟢: (LocationManager) - Initialize Location Services inside init()")
}
func startUpdatingLocation() {
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
func requestLocation() {
locationManager.requestLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.last else { return }
DispatchQueue.main.async {
self.userLocation = location
log.info("\n 🟡: (LocationManager) - Setup new location as: \(location)")
self.defaultRegion = MKCoordinateRegion(center: location.coordinate, span: USER_LOCATION_SPAN)
log.info("\n 🟡: (LocationManager) - Setup default region as \(location.coordinate.latitude) and \(location.coordinate.longitude).")
self.locationManager.stopUpdatingLocation()
log.info("\n 🟡: (LocationManager) - Stop updating the location.")
}
}
}
Then I am utilizing it in two separate view files called MapUIView and MapUIView2 and I have the following object in both:
#ObservedObject var locationManager = LocationManager.getInstance
This causes the DispatchQueue.main.async inside didUpdateLocations to run through twice on application start - Is this normal behavior or is it possible to have the didUpdateLocations to run just once, but handle multiple views?
I am using the following observable object to track the users location:
import Foundation
import MapKit
class LocationManager: NSObject, ObservableObject {
private let locationManager = CLLocationManager()
#Published var location: CLLocation? = nil
override init() {
super.init()
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.distanceFilter = kCLDistanceFilterNone
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
}
func locationServicesEnabled() -> Bool {
return self.locationManager.locationServicesEnabled()
}
}
extension LocationManager: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.last else {
return
}
self.location = location
}
}
However, when I try to compile I get an error next to the return self.locationManager.locationServicesEnabled() statement. The compiler says: Static member 'locationServicesEnabled' cannot be used on instance of type 'CLLocationManager', Replace 'self.locationManager' with 'CLLocationManager'. I do not understand this error because self.locationManager is an instance of CLLocationManager. Please help.
Static means that locationServicesEnabled is a member of the class, not of the object. Use the classname CLLocationManager as suggested.
Seems like the API has changed, earlier it was an instance method, now it is a class method:
https://developer.apple.com/documentation/corelocation/cllocationmanager/1620566-locationservicesenabled
static func configureLocationManager(manager: CLLocationManager, delegate: CLLocationManagerDelegate?) {
manager.allowsBackgroundLocationUpdates = true
manager.delegate = delegate
manager.desiredAccuracy = kCLLocationAccuracyThreeKilometers
switch manager.authorizationStatus {
case .authorizedAlways, .authorizedWhenInUse:
if CLLocationManager.locationServicesEnabled() {
manager.requestLocation()
}
default:
manager.requestWhenInUseAuthorization()
}
}
Here a piece of code that configured location manager and checks whether the app was allowed by user to use location services.
Here is more code that could be useful. This is a file that I created to implement the delegate methods.
https://github.com/aibo-cora/Safe-Bavaria/blob/main/Safe%20Bavaria/View%20Model%20-%20Utility/Find.User.Location.swift
I wrote a program that uses LocationManagerDelegate to display coordinates in the debug area whenever the current location changes. Got an error when retrieving coordinates
Can not use instance member 'locationManager' within property initializer; property initializers run before 'self' is available
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate{
var locationManager: CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
setUpLocationManager()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setUpLocationManager() {
locationManager = CLLocationManager()
guard let locationManager = locationManager else {return}
locationManager.requestWhenInUseAuthorization()
let status = CLLocationManager.authorizationStatus()
if status == .authorizedWhenInUse {
locationManager.delegate = self
locationManager.distanceFilter = 10
locationManager.startUpdatingLocation()
printLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) ->Optional<Any> {
let location = locations.first
let latitude = location?.coordinate.latitude
let longitude = location?.coordinate.longitude
let latlong = [latitude, longitude]
return latlong
}
let myLocation = locationManager()
func printLocation() {
print("test\(myLocation)")
}
}
test (Function)
is output
let myLocation = locationManager ()
When you change to
let myLocation = locationManager
Your code contains a few mistakes.
The error occurs because you cannot execute the affected line on the top level of the class.
First of all you must not change signatures of delegate methods. This custom delegate method
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) ->Optional<Any> { ...
will never be called.
And apart from that why do you declare the return type as Any? although it's supposed to be [CLLocationCoordinate2D]?
Create the location manager immediately, replace
var locationManager: CLLocationManager!
with
let locationManager = CLLocationManager()
In setUpLocationManager() delete the lines
locationManager = CLLocationManager()
guard let locationManager = locationManager else {return} // this line is completely pointless anyway
printLocation()
The delegate method didUpdateLocations is called periodically and asynchronously. Print the result inside the method
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.first else { return }
let latitude = location.coordinate.latitude
let longitude = location.coordinate.longitude
let latlong = [latitude, longitude]
print("test", latlong)
}
Delete
let myLocation = locationManager()
func printLocation() {
print("test\(myLocation)")
}
didUpdateLocations is not firing
- CLLocationManagerDelegate was implemented correctly with the viewcontroller as a delegate
import Foundation
import UIKit
import CoreLocation
protocol LocationServiceDelegate {
func tracingLocation(currentLocation: CLLocation)
func tracingLocationDidFailWithError(error: NSError)
}
class LocationService: NSObject, CLLocationManagerDelegate {
static var sharedInstance = LocationService()
var locationManager: CLLocationManager?
var currentLocation: CLLocation?
var delegate: LocationServiceDelegate?
var paymentVC: PaymentViewController?
override init() {
super.init()
self.locationManager = CLLocationManager()
guard let locationManager = self.locationManager else {
return
}
if CLLocationManager.authorizationStatus() == .notDetermined {
locationManager.requestAlwaysAuthorization()
}
locationManager.distanceFilter = 200
}
func startUpdatingLocation() {
print("Starting Location Updates")
self.locationManager!.startUpdatingLocation()
}
func stopUpdatingLocation() {
print("Stop Location Updates")
self.locationManager?.stopUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.last else {
return
}
self.currentLocation = location
updateLocation(currentLocation: location)
}
private func locationManager(manager: CLLocationManager, didFailWithError error: Error) {
updateLocationDidFailWithError(error: error as NSError)
}
private func updateLocation(currentLocation: CLLocation){
guard let delegate = self.delegate else {
return
}
delegate.tracingLocation(currentLocation: currentLocation)
}
private func updateLocationDidFailWithError(error: NSError) {
guard let delegate = self.delegate else {
return
}
delegate.tracingLocationDidFailWithError(error: error)
}
}
this is the extension of the viewcontroller where I implement to custom protocole for corelocation tracking
I call startUpdatingLocations() in viewDidLoad
extension PaymentViewController: LocationServiceDelegate,CLLocationManagerDelegate {
func tracingLocation(currentLocation: CLLocation) {
locationService.currentLocation = currentLocation
}
func tracingLocationDidFailWithError(error: NSError) {
print("Error message: \(error.localizedDescription)")
}
func startUpdatingLocations() {
locationService.locationManager?.delegate = self
locationService.delegate = self
locationService.startUpdatingLocation()
}
func stopUpdatingLocations() {
LocationService.sharedInstance.stopUpdatingLocation()
}
}
the corelocation tracking is not firing in the simulator. However this is enabled.
enter image description here
unfortunately, I have no way to test with a device right now
The only way I know of to simulate core location tracking on a simulator is by choosing one of the location options available in debug tab of the simulator.
I am trying to use the below LocationSingleton Class from this blog in my project. I like the simplicity of its usage.
You start updating location by simply calling:
LocationSingleton.sharedInstance.startUpdatingLocation()
Get the last location by simply calling:
LocationSingleton.sharedInstance.lastLocation
My intention is to start location services, get the last location so that I can then fetch users from Firebase using the location returned.
The issue is that if I call lastLocation straight after startUpdatingLocation it returns nil.
After some debugging I've found the reason is because location services are slow to start on the device and therefore when lastLocation is called the devices hasn't acquired the location yet. I would like to execute the next command as soon as the lastLocation has been recorded. How can I achieve that?
I would like to understand how the Protocol is being used?
import UIKit
import CoreLocation
protocol LocationServiceDelegate {
func locationDidUpdateToLocation(currentLocation: CLLocation)
func locationUpdateDidFailWithError(error: NSError)
}
class LocationSingleton: NSObject,CLLocationManagerDelegate {
var locationManager: CLLocationManager?
var lastLocation: CLLocation?
var delegate: LocationServiceDelegate?
static let sharedInstance:LocationSingleton = {
let instance = LocationSingleton()
return instance
}()
override init() {
super.init()
self.locationManager = CLLocationManager()
guard let locationManagers=self.locationManager else {
return
}
if CLLocationManager.authorizationStatus() == .notDetermined {
//locationManagers.requestAlwaysAuthorization()
locationManagers.requestWhenInUseAuthorization()
}
if #available(iOS 9.0, *) {
// locationManagers.allowsBackgroundLocationUpdates = true
} else {
// Fallback on earlier versions
}
locationManagers.desiredAccuracy = kCLLocationAccuracyBest
locationManagers.pausesLocationUpdatesAutomatically = false
locationManagers.distanceFilter = 0.1
locationManagers.delegate = self
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.last else {
return
}
self.lastLocation = location
updateLocation(currentLocation: location)
}
#nonobjc func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
switch status {
case .notDetermined:
locationManager?.requestWhenInUseAuthorization()
break
case .authorizedWhenInUse:
locationManager?.startUpdatingLocation()
break
case .authorizedAlways:
locationManager?.startUpdatingLocation()
break
case .restricted:
// restricted by e.g. parental controls. User can't enable Location Services
break
case .denied:
// user denied your app access to Location Services, but can grant access from Settings.app
break
default:
break
}
}
// Private function
private func updateLocation(currentLocation: CLLocation){
guard let delegate = self.delegate else {
return
}
delegate.locationDidUpdateToLocation(currentLocation: currentLocation)
}
private func updateLocationDidFailWithError(error: NSError) {
guard let delegate = self.delegate else {
return
}
delegate.locationUpdateDidFailWithError(error: error)
}
func startUpdatingLocation() {
print("Starting Location Updates")
self.locationManager?.startUpdatingLocation()
// self.locationManager?.startMonitoringSignificantLocationChanges()
}
func stopUpdatingLocation() {
print("Stop Location Updates")
self.locationManager?.stopUpdatingLocation()
}
func startMonitoringSignificantLocationChanges() {
self.locationManager?.startMonitoringSignificantLocationChanges()
}
}
The location manager works asynchronously and provides delegate methods to get the result.
In your class adopt LocationServiceDelegate, implement the delegate methods and set the delegate for example in viewDidLoad
func locationDidUpdateToLocation(currentLocation: CLLocation)
{
print(LocationSingleton.sharedInstance.lastLocation)
}
func locationUpdateDidFailWithError(error: NSError)
{
print(error)
}
func viewDidLoad()
super viewDidLoad()
let locationSingleton = LocationSingleton.sharedInstance
locationSingleton.delegate = self
locationSingleton.startUpdatingLocation()
}
When a location is detected, one of the delegate methods is called