JSON Post方法不能快速工作

时间:2017-12-13 18:10:17

标签: ios json swift google-maps

我在swift中解析谷歌地图api中的json数据,我试图使用谷歌地图api显示当前位置,使用didUpdateLocations获取当前位置纬度和经度。在serviceLocationupdate()内 使用post方法发布lat和long值但是没有从json获得响应。如何从json获取响应(数据)。

这是代码

var lat  = ""
var long = ""
var latlng:String = ""


         func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

                let location:CLLocationCoordinate2D = manager.location!.coordinate
                self.lat = String(location.latitude)
                self.long = String(location.longitude)
                latlng = self.lat+"," + self.long


}



func serviceLocationupdate()
        {

            var request = URLRequest(url: URL(string: "http://maps.googleapis.com/maps/api/geocode/json")!)

     let session = URLSession.shared

            request.httpMethod = "POST"

      ----->> let bodyData = "latlng=\(latlng)&sensor=\("true")"

            print("bodydata",bodyData)

            request.httpBody = bodyData.data(using: String.Encoding.utf8);


            let task = session.dataTask(with:request,completionHandler:{(d,response,error)in

                do{


                    if let data = d{
                        do{
                            let jsonResult = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
                            if let results = jsonResult["results"] as? [[String : AnyObject]] {

                                for result in results{

                                    if let addressComponents = result["address_components"] as? [[String : AnyObject]] {

                                        print(addressComponents)
                                    }
                                }
                            }

                        } catch
                        {

                        }

                    }

            }
            })

            task.resume()
        }

如果我可以使用这个api工作正常得到正确的数据

var request = URLRequest(url:URL(string:" http://maps.googleapis.com/maps/api/geocode/json?latlng=13.026811,77.593773&sensor=true")!)

我希望使用纬度和经度显示当前位置

2 个答案:

答案 0 :(得分:0)

这适用于游乐场:

//: Playground - noun: a place where people can play

import UIKit
import XCTest
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

func serviceLocationupdate()
{
    let session = URLSession.shared
    if let url = URL(string: "http://maps.googleapis.com/maps/api/geocode/json"),
        var params = URLComponents(url: url, resolvingAgainstBaseURL: false) {

        params.queryItems = [URLQueryItem]()
        params.queryItems?.append(URLQueryItem(name: "latlng", value: "33.9250675,-84.339827"))
        params.queryItems?.append(URLQueryItem(name: "sensor", value: "true"))

        guard let finalURL = params.url else {
            print("Failed to create URL")
            return
        }
        var request = URLRequest(url: finalURL)
        request.httpMethod = "POST"

        let task = session.dataTask(with:request,completionHandler:{(data,response,error)in

            if let error = error {
                print("Error is \(error)")
                return
            }

            if let resp = response as? HTTPURLResponse {
                print("Response status code \(resp.statusCode)")

                guard let data = data else {
                    return
                }

                do {
                    if let jsonResult = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary,
                        let results = jsonResult["results"] as? [[String : AnyObject]] {

                        for result in results {
                            if let addressComponents = result["address_components"] as? [[String : AnyObject]] {
                                print(addressComponents)
                            }
                        }

                    } else {
                        print("Could not coerce into a dictionary")
                    }
                } catch _ {
                    print("An error occurred")
                }


            } else {
                print("Invalid response")
            }
        })
        task.resume()
    }
}

serviceLocationupdate()

答案 1 :(得分:0)

看起来API与您提到的网址(http://maps.googleapis.com/maps/api/geocode/json?latlng=13.026811,77.593773&sensor=true)一起使用,然后您可以使用GET代替POST。请尝试以下方法:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

            let location:CLLocationCoordinate2D = manager.location!.coordinate
            self.lat = String(location.latitude)
            self.long = String(location.longitude)
            latlng = self.lat+","+self.long
            serviceLocationupdate()
}

func serviceLocationupdate()
    {

        var request = URLRequest(url: URL(string: "http://maps.googleapis.com/maps/api/geocode/json?latlng=\(latlng)&sensor=true")!)

        let task = session.dataTask(with:request,completionHandler:{(d,response,error)in

                if let data = d{
                    do{
                        let jsonResult = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
                        if let results = jsonResult["results"] as? [[String : AnyObject]] {

                            for result in results{

                                if let addressComponents = result["address_components"] as? [[String : AnyObject]] {

                                    print(addressComponents)
                                }
                            }
                        }

                    } catch
                    {

                    }

                }
        })

        task.resume()
    }