Rohit
Rohit

Reputation: 2326

Pass Current Location in Parameter Swift

I am trying to pass the current user location in parameters to get the desired result. I am getting current location like this in my viewDidLoad Method:-

self.locationManager.requestAlwaysAuthorization()

self.locationManager.requestWhenInUseAuthorization()

if CLLocationManager.locationServicesEnabled() {
     locationManager.delegate = self
     locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
     locationManager.startUpdatingLocation()
 }

After that I called didUpdateLocations method to get current location co-ordinates and created two variables in which I stored current location.

var latitude: String = ""
var longitude: String = ""

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let locValue: CLLocationCoordinate2D = manager.location?.coordinate else { return }
        print("locations = \(locValue.latitude) \(locValue.longitude)")
        self.latitude = "\(locValue.latitude)" ; self.longitude = "\(locValue.latitude)"
        print(self.latitude, self.longitude)
    }

But when I am trying to pass my current location in parameters I am getting no value.

let param: [String : Any] =
                                 ["lat": self.latitude,
                                  "lng": self.longitude,
                                  "truck_type": "2",
                                  "title": "home",
                                  "job_type": "Jobs"


                                 ]
    print(param)
    CommonUtils.showHudWithNoInteraction(show: true)

    Alamofire.request("api", method: .post, parameters: param, encoding: JSONEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in

        CommonUtils.showHudWithNoInteraction(show: false)
        switch(response.result) {
        case .success(_):
            if let json = response.result.value as? [String:Any] {
                print(json)

                DispatchQueue.main.async {
                    self.fleetOwnerTableView.reloadData()
                }
            }

            break

        case .failure(_):
            print("Error")
            break

        }
    }

enter image description here I don't know what am I doing wrong. How can I pass current location into parameters?

Upvotes: 0

Views: 854

Answers (2)

RajeshKumar R
RajeshKumar R

Reputation: 15748

Update the didUpdateLocations method to call the api and pass the current location

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let location = locations.last {
        callAPI(location: location.coordinate)
    }
}

Your api calling method

func callAPI(location:CLLocationCoordinate2D) {
    let param: [String : Any] =
        ["lat": "\(location.latitude)",
         "lng": "\(location.longitude)",
         "truck_type": "2",
         "title": "home",
         "job_type": "Jobs"
    ]
    //Alamofire.request
}

Upvotes: 2

Nitish
Nitish

Reputation: 14113

Why to pass them as parameter. Make your Location manager as a singleton.

class LocationManager: NSObject, CLLocationManagerDelegate {

    static let shared = LocationManager()

    let locationManager : CLLocationManager

    override init() {
        locationManager = CLLocationManager()
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        super.init()
        locationManager.delegate = self
    }

    func start() {
        locationManager.requestAlwaysAuthorization()
        locationManager.startUpdatingLocation()
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let mostRecentLocation = locations.last else {
            return
        }

        print(mostRecentLocation)
    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print(error)
        locationManager.stopUpdatingLocation()
    }
} 

Just call LocationManager.shared.start() to start the location updates and boom, you'll have the current location anytime in your app. You can of course create stop function to stop the location service once you are done.

Upvotes: 0

Related Questions