Alex Ritter
Alex Ritter

Reputation: 1041

Swift unwanted URL percent encoding

I'm trying to format a URL for use in accessing an API. The documentation for the api specifies a URL that contains the "[" and "]" characters in it. When I create a URL from my string in Swift, it is adding percent encoding and changing these characters to "%5B" and "%5D".

How do I tell swift to not percent encode these characters? Thanks!

func attemptPubgIDLookup (playerName: String, completion: @escaping (String) -> Void) {
let region = "pc-na"
let urlString = "https://api.playbattlegrounds.com/shards/" + region + "/players?filter[playerNames]=" + playerName
let finalUrl = URL(string:urlString)
if let finalUrl = finalUrl {

    var urlRequest = URLRequest(url: finalUrl)
    urlRequest.httpMethod = HTTPMethod.get.rawValue

    urlRequest.addValue(pubgApiKey, forHTTPHeaderField: "Authorization: Bearer")
    urlRequest.addValue("application/vnd.api+json", forHTTPHeaderField: "Accept")

    Alamofire.request(urlRequest)
        .responseJSON(completionHandler: { (response) in
            debugPrint(response)
        })
}
}

Upvotes: 0

Views: 358

Answers (1)

Martin Muldoon
Martin Muldoon

Reputation: 3428

That's what you want. When the server receives your request it will decode the URL...

%5B is '[' and %5D is ']'

This is called percent encoding and is used in encoding special characters in the url parameter values.

Upvotes: 1

Related Questions