如何将用户当前的时间更新到API服务器?

时间:2018-12-15 11:29:39

标签: ios location

我有一个项目,需要在该项目中更新API服务器上用户的当前位置坐标。我该如何实现?持续调用API是个好主意(我认为不是)吗?

我需要不断更新坐标,以便其他用户在我们第一次看到我附近的驾驶员时就可以在Uber应用程序中看到我。

2 个答案:

答案 0 :(得分:0)

也许您可以实施timer,并通过定期发送经纬度来发出POST请求。

class ViewController: UIViewController {
    var timer: Timer!

    override func viewDidLoad() {
        timer = Timer.scheduledTimer(timeInterval: 10.0, target: self, selector: #selector(makeRequest), userInfo: nil, repeats: true)

    }


    @objc func makeRequest() {
        // make your post request here.
    }        

 }

例如,上面给出的计时器将每10秒调用一次makeRequest方法。

如果您对网络了解不多,请对以下主题进行研究:

快速网络层,Alamofire,URLSession

答案 1 :(得分:0)

**Step 1 :- Get latitude and long. of the user first.**

Reference URL:- https://stackoverflow.com/questions/12736086/how-to-get-location-latitude-longitude-value-in-variable-on-ios

**Step 2:- Define following variables globally.**

    var timer:Timer? 

    var sourceLatitude = CLLocationDegrees()

    var sourceLongitude = CLLocationDegrees()

**Step 3:- Setup timer for continuous update as below.**

override func viewDidLoad() 
{
   super.viewDidLoad()

   timer = Timer.scheduledTimer(timeInterval: 15, target: self, selector: #selector(self.updateDriverLoction), userInfo: nil, repeats: true)
    }


**Step 4:- call appropriate method for sending and updating lat. long. to the server using any of networking API.(In my case I have used Alamofire)**

 // must be internal or public.

    @objc func updateDriverLoction() {

        if Reachability.isConnectedToNetwork() {

                let param1:[String:String] = [
                    "latitude" : "\(sourceLatitude)",
                    "longitude" : "\(sourceLongitude)"
                ]
                ServerClass.sharedInstance.putRequestWithUrlParameters(param1, path: BASE_CAB_URL + PROJECT_URL.UPDATE_DRIVER_LOCATION_API, successBlock: { (json) in
                    print(json)
                    let success = json["success"].stringValue
                    if success  == "true"  {
                    }
                    else {
                    }
                }, errorBlock: { (NSError) in
                    //                UIAlertController.showInfoAlertWithTitle("Alert", message:  kUnexpectedErrorAlertString, buttonTitle: "Okay")
                })
            }
        }
        else{
            UIAlertController.showInfoAlertWithTitle("Alert", message: "Please Check internet connection", buttonTitle: "Okay")
        }

}