-1

Thanks for the tremendous helps, I was able to get lat and lng by using Google geocoding API with swift. If anyone encounters some problems, hope this helps!

here is the code.

var components = URLComponents(string: "https://maps.googleapis.com/maps/api/geocode/json")!
            let key = URLQueryItem(name: "key", value: "YOUR_KEY")
            let address = URLQueryItem(name: "address", value: TOKYO)
            components.queryItems = [key, address]

            let task = URLSession.shared.dataTask(with: components.url!) { data, response, error in

                guard let data = data, let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200, error == nil else {
                    print(String(describing: response))
                    print(String(describing: error))
                    return
                }

                guard let json = try! JSONSerialization.jsonObject(with: data) as? [String: Any] else {
                    print("not JSON format expected")
                    print(String(data: data, encoding: .utf8) ?? "Not string?!?")
                    return
                }

                guard let results = json["results"] as? [[String: Any]],
                    let geometry = results[0]["geometry"] as? [String:AnyObject],
                    let location = geometry["location"] as? [String:Double],
                    let lat = location["lat"],
                    let lng = location["lng"],
                    let status = json["status"] as? String,
                    status == "OK"
                    else{return}
Daibaku
  • 11,416
  • 22
  • 71
  • 108

3 Answers3

0

Take a look at,

 stringByAddingPercentEscapesUsingEncoding

for ios 8 and prior.

from ios 9,

   stringByAddingPercentEncodingWithAllowedCharacters

Your code should be like,

  let jsonUrl = "https://maps.googleapis.com/maps/api/geocode/json?address=Tokyo&key=Mykey"



   let yourFinalString = jsonUrl.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)

    guard URL(string:yourFinalString!) != nil else {

        return print("error")

    }

If your url string have some special characters then you have to escapes it by utf8 encoding!

Ketan Parmar
  • 27,092
  • 9
  • 50
  • 75
0

For constructing URLs with query params I recommend to use URLComponents:

var constructor = URLComponents()
constructor.scheme = "https"
constructor.host = "maps.googleapis.com"
constructor.path = "/maps/api/geocode/json"
constructor.queryItems = [
    URLQueryItem(name: "address", value: "Tokyo"),
    URLQueryItem(name: "key", value: "MyKey")
]
constructor.url // https://maps.googleapis.com/maps/api/geocode/json?address=Tokyo&key=MyKey

or

var constructor = URLComponents(string: "https://maps.googleapis.com/maps/api/geocode/json")
constructor?.queryItems = [
    URLQueryItem(name: "address", value: "Tokyo"),
    URLQueryItem(name: "key", value: "MyKey")
]
constructor?.url // https://maps.googleapis.com/maps/api/geocode/json?address=Tokyo&key=MyKey

It will format and escape all the characters internally, using proper allowed characters list.

user28434'mstep
  • 6,290
  • 2
  • 20
  • 35
0

Check this out:

var components = URLComponents(string: "https://maps.googleapis.com/maps/api/geocode/json")!
let key = URLQueryItem(name: "key", value: "AIzaSyCbFUri87RMHBX42AsOuxDQANeDCCK8LkA") // use your key
let address = URLQueryItem(name: "address", value: "Tokyo")
components.queryItems = [key, address]

let task = URLSession.shared.dataTask(with: components.url!) { data, response, error in

    guard let data = data, let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200, error == nil else {
        print(String(describing: response))
        print(String(describing: error))
        return
    }

    guard let json = try! JSONSerialization.jsonObject(with: data) as? [String: Any] else {
        print("not JSON format expected")
        print(String(data: data, encoding: .utf8) ?? "Not string?!?")
        return
    }

    guard let results = json["results"] as? [[String: Any]],
        let status = json["status"] as? String,
        status == "OK" else {
            print("no results")
            print(String(describing: json))
            return
    }
}

task.resume()
Sivajee Battina
  • 4,124
  • 2
  • 22
  • 45
  • It perfectly worked!! Thank you so much!! How can I parse only "lat" and "lng"? I've been trying on my own but still can't figure it out. I'm sorry I'm pretty new in programming. hope you understand. – Daibaku Nov 21 '17 at 16:51
  • Please accept the answer, so that it might helpful for another person like you. As you are new, please try to get values from dictionary, lat & lng. In worst case I will help you out. ;-) – Sivajee Battina Nov 21 '17 at 18:05
  • I did sorry I didn't know how this works because this is my first time to ask a question. I'll do my best to work it out thank you so much again really appreciate it!! – Daibaku Nov 22 '17 at 00:35