简体   繁体   English

在参数Swift中传递当前位置

[英]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:- 我在viewDidLoad方法中得到这样的当前位置:-

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. 之后,我调用didUpdateLocations方法获取当前位置坐标,并创建了两个用于存储当前位置的变量。

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

        }
    }

在此处输入图片说明 I don't know what am I doing wrong. 我不知道我在做什么错。 How can I pass current location into parameters? 如何将当前位置传递给参数?

Update the didUpdateLocations method to call the api and pass the current location 更新didUpdateLocations方法以调用api并传递当前位置

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

Your api calling method 您的api调用方法

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

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. 只需调用LocationManager.shared.start()开始位置更新和繁荣,您就可以随时在您的应用中获得当前位置。 You can of course create stop function to stop the location service once you are done. 当然,您可以创建停止功能以在完成后停止定位服务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM