0
votes

I am Parsing json data from google maps api in swift, am trying to show current location using google maps api, getting current location latitude and longitude using didUpdateLocations. inside the serviceLocationupdate() posting lat and long values using post method but am not getting the response from the json. how can I get the response(data) from the json.

this is the code

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()
        }

if i can use this api its working fine getting proper data

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

I want display the current location using latitude and longitude

2

2 Answers

0
votes

This works in a playground:

//: 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()
0
votes

Looks like the API works with the url you mentioned (http://maps.googleapis.com/maps/api/geocode/json?latlng=13.026811,77.593773&sensor=true), then you can just use GET instead of POST. Try the following:

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()
    }