Search code examples
swiftswiftuicoordinatescore-locationcllocation

Swift: Get Current User Coordinates and Store them into a Variable


I am currently trying to get the current coordinates of the user and ultimately store those values into variables.

I have created the following class to define the users current location and set up functions to pull data.

import Foundation
import CoreLocation

class MyCurrentCoordinate: NSObject {


     private var currentLocation: CLLocation!

     var myLatitude = 0.0
     var myLongitude = 0.0
     var myAltitude = 0.0

     override init() {
         super.init()
     }

     func getLat() {
         myLatitude = currentLocation.coordinate.latitude
     }

     func getLong() {
         myLongitude = currentLocation.coordinate.longitude
     }

     func getAlt() {
         myAltitude = currentLocation.altitude
     }
}

This does not show any errors. However, when I go to call any function (getLat, getLong, or getAlt) to pull a piece of the users location data, the app crashes due the value being nil. Does anyone have any insight as to why the actual user lat, long, or altitude is not being passed?

I have the location permission and info.plist updated to allow the user to give location tracking permission.


Solution

  • import Foundation
    import CoreLocation
    import UIKit
    
    public protocol LocalizationHelperDelegate: class {
        func didUpdateLocation(_ sender: CLLocation)
    }
    
    public class LocalizationHelper: NSObject {
    
        public weak var delegate: LocalizationHelperDelegate?
        public static var shared = LocalizationHelper()
    
        private lazy var locationManager: CLLocationManager = {
            let locationManager = CLLocationManager()
            locationManager.requestAlwaysAuthorization()
            locationManager.allowsBackgroundLocationUpdates = true
            locationManager.pausesLocationUpdatesAutomatically = false
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            return locationManager
        }()
    
        private var currentLocation: CLLocationCoordinate2D?
    
        public func startUpdatingLocation() {
            locationManager.delegate = self
            locationManager.startUpdatingLocation()
        }
    
        public func stopUpdatingLocation() {
            locationManager.stopUpdatingLocation()
        }
    
        public func getCurrentLocation() -> CLLocationCoordinate2D? {
            return currentLocation
        }
    
        public func getLat() -> Double{
            return currentLocation?.latitude ?? 0.0
        }
    
        public func getLon() -> Double{
            return currentLocation?.longitude ?? 0.0
        }
    
    
    }
    
    extension LocalizationHelper: CLLocationManagerDelegate {
    
        public func locationManager(_: CLLocationManager, didUpdateLocations locations: [CLLocation]){
            guard let location = locations.first else { return }
            currentLocation = location.coordinate
            print("[Update location at - \(Date())] with - lat: \(currentLocation!.latitude), lng: \(currentLocation!.longitude)")
            delegate?.didUpdateLocation(location)
        }
    }
    

    How to use

    LocalizationHelper.shared.Start()
    ...
    let lat = LocalizationHelper.shared.getLat()
    let lon = LocalizationHelper.shared.getLon()
    ...
    LocalizationHelper.shared.Stop()