1

As the title, I am using Google Places API, the URL has a question mark, when I send a request, it will become %3F, how can I modify my code by Swift 4.2??

I found a lot of information but they were using Swift 2 or 3, so it is unavailable for me!

UPDATE my code

let urlString = "\(GOOGLE_MAP_API_BASEURL)key=\(GMS_HTTP_KEY)&input=\(keyword)&sessiontoken=\(ver4uuid!)"
        print(urlString)
        if let encodedString = urlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.alphanumerics
            .union(CharacterSet.urlPathAllowed)
            .union(CharacterSet.urlHostAllowed)) {
            print("encodedString: \(encodedString)")
Berlin
  • 65
  • 1
  • 8

2 Answers2

1

You are supposed to encode only the query parameters (although probably only keyword actually needs encoding), not the whole URL.

func urlEncode(_ string: String) -> String {
    var allowed = CharacterSet.urlQueryAllowed
    allowed.remove(charactersIn: "!*'();:@&=+$,/?%#[]")
    return string.addingPercentEncoding(withAllowedCharacters: allowed) ?? ""
)

let urlString = "\(GOOGLE_MAP_API_BASEURL)key=\(urlEncode(GMS_HTTP_KEY))&input=\(urlEncode(keyword))&sessiontoken=\(urlEncode(ver4uuid!))"
print(urlString)

Also see Swift - encode URL about the correct way to encode URL parameters.

Sulthan
  • 128,090
  • 22
  • 218
  • 270
1

In this case I highly recommend to use URLComponents and URLQueryItem which handles the percent escaping very smoothly.

var urlComponents = URLComponents(string: GOOGLE_MAP_API_BASEURL)!
let queryItems = [URLQueryItem(name: "key", value: GMS_HTTP_KEY),
                  URLQueryItem(name: "input", value: keyword),
                  URLQueryItem(name: "sessiontoken", value: ver4uuid!)]
urlComponents.queryItems = queryItems
let url = urlComponents.url!
vadian
  • 274,689
  • 30
  • 353
  • 361