Jake
Jake

Reputation: 13761

Issue with url Decode in iOS

I'm trying to decode a url that has another url (separately encoded) as a query parameter:

com.testScheme://openurl?url=https%3A%2F%2Fm%2Euber%2Ecom%2Ful%3Faction%3DsetPickup%26pickup%3Dmy%5Flocation%26dropoff%5Bformatted%5Faddress%5D%3D5394%2520General%2520Hood%2520Trl%2C%2520Nashville%2520TN

However, the code below seems to be "double decoding" the twice encoded url.

guard let urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false),
    let requestType = urlComponents.host else {
       return false
}

if requestType.lowercased() == "openurl" {
    guard let queryItems = urlComponents.queryItems,
        let urlString = queryItems.filter({ $0.name == "url" }).first?.value?.removingPercentEncoding,
        let url = URL(string: urlString) else {
        //unable to get parameters
        return false
    }

    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + DispatchTimeInterval.milliseconds(25)) {
        UIApplication.shared.openURL(url)
    }            

    return true
}

Output of urlString:

https://m.uber.com/ul?action=setPickup&pickup=my_location&dropoff[formatted_address]=5394 General Hood Trl, Nashville TN

I need urlString to be:

https://m.uber.com/ul?action=setPickup&pickup=my_location&dropoff[formatted_address]=5394%20General%20Hood%20Trl,%20Nashville%20TN

Why is the "double decoding" occurring and how might I fix it?

Upvotes: 3

Views: 2644

Answers (1)

Inder Kumar Rathore
Inder Kumar Rathore

Reputation: 39988

Try removing removingPercentEncoding from the below line

let urlString = queryItems.filter({ $0.name == "url" }).first?.value?.removingPercentEncoding

Upvotes: 2

Related Questions