-1

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.

JBrum
  • 25
  • 2

2 Answers2

0

You can use CLLocationManager

  1. Add app capability, you can open your info.plist like source code and add:

    <key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
    <string>App requires allways tracking</string>
    <key>NSLocationAlwaysUsageDescription</key>
    <string>App requires background tracking</string>
    <key>NSLocationWhenInUseUsageDescription</key>
    <string>App requires tracking when be in use</string>
    
    <key>UIBackgroundModes</key>
    <array>
        <string>fetch</string>
        <string>location</string>
        <string>remote-notification</string>
    </array>
    
  2. Ask for authorization like locationManager.requestAlwaysAuthorization() and manage if have the correct access... CLLocationManager.authorizationStatus() == .authorizedAlways

    import CoreLocation
    
    class ViewController: UIViewController, CLLocationManagerDelegate {
        var locationManager: CLLocationManager?
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            locationManager = CLLocationManager()
            locationManager?.delegate = self
            locationManager?.requestAlwaysAuthorization()
            if CLLocationManager.authorizationStatus() == .authorizedAlways {
                locationManager.allowsBackgroundLocationUpdates = true
                locationManager.pausesLocationUpdatesAutomatically = false
                locationManager.desiredAccuracy = kCLLocationAccuracyBest
                locationManager.startUpdatingLocation()
            }
            if CLLocationManager.authorizationStatus() == .authorizedWhenInUse {
                locationManager.allowsBackgroundLocationUpdates = false
                locationManager.pausesLocationUpdatesAutomatically = true
                locationManager.desiredAccuracy = kCLLocationAccuracyBest
                locationManager.startUpdatingLocation()
            }
        }
    }
    
    extension ViewController: CLLocationManagerDelegate {
    
        public func locationManager(_: CLLocationManager, didUpdateLocations locations: [CLLocation]){
            guard let location = locations.first else { return }
            print(location)
    
        }
    
        public func locationManager(_: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
            switch status {
            case .notDetermined:
                print("Autorization status did change \(status)")
            case .authorizedWhenInUse:
                print("Autorization status did change \(status)")
            case .authorizedAlways:
                print("Autorization status did change \(status)")
            case .restricted:
                print("Autorization status did change \(status)")
            case .denied:
                print("Autorization status did change \(status)")
            @unknown default:
                fatalError()
            }
        }
    }
    
  3. Don't forget to stop it in some place locationManager.stopUpdatingLocation()

Enzo N. Digiano
  • 370
  • 3
  • 6
0
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()
Enzo N. Digiano
  • 370
  • 3
  • 6