kiran
kiran

Reputation: 4409

How to remove special characters from url?

let ids = [String: [String]]

ids=%5B%4566abef1c-4462-4g62-bcc5-5ae10547104c%22,%20%1256efcf8c-6977-430d-b3ec-4ae80547101c%22%5D

After appended and passing url params, response failing in response structure special symbol added in -> %5B%%

https://baseUrl/endpoint?ids=4566abef1c-4462-4g62-bcc5-5ae10547104c,1256efcf8c-6977-430d-b3ec-4ae80547101c

How to remove %22%5D from url?

Here Code:

let parms: [String: [String]]
let urlString = "\(baseUrl)/\(endpoint)"
Connector.requestSwiftyJson(
    url: urlString,
    requestType: .get,
    withParams: parms,
    loader: false
) { json, response, error in

Upvotes: 0

Views: 3978

Answers (3)

vadian
vadian

Reputation: 285059

There is an API to remove the percent encoding

let string = "ids=%5B%4566abef1c-4462-4g62-bcc5-5ae10547104c%22,%20%1256efcf8c-6977-430d-b3ec-4ae80547101c%22%5D"
let cleanedString = string.removingPercentEncoding

However if you need to extract the UUIDs you can do it with Regular Expression

func extractUUID(from string : String) -> [String]
{
    let pattern = "[0-9a-f]{10}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"
    let regex = try! NSRegularExpression(pattern: pattern)
    let matches = regex.matches(in: string, range: NSRange(string.startIndex..., in: string))
    return matches.map { match -> String in
        let range = Range(match.range, in: string)!
        return String(string[range])
    }
}

let uuids = extractUUID(from: "ids=%5B%4566abef1c-4462-4g62-bcc5-5ae10547104c%22,%20%1256efcf8c-6977-430d-b3ec-4ae80547101c%22%5D")
print(uuids)

Note: the g in the first UUID is an invalid character

Upvotes: 1

"...How to remove %22%5D from url? ". Try this:

 let ids = "%5B%4566abef1c-4462-4g62-bcc5-5ae10547104c%22,%20%1256efcf8c-6977-430d-b3ec-4ae80547101c%22%5D"
 let cleanUrl = ids.replacingOccurrences(of: "%22%5D", with: "")
 print("\n---> cleanUrl: \(cleanUrl) \n")

You can also remove all percent encoding using this:

   if let cleanUrl = ids.replacingOccurrences(of: "%5B", with: "") // [
    .replacingOccurrences(of: "%5D", with: "")  // ]
    .replacingOccurrences(of: "%22", with: "")  // "
    .removingPercentEncoding {  // other encoding
    
    print("\n---> cleanUrl: \(cleanUrl) \n")
}

Upvotes: 0

Mojtaba Hosseini
Mojtaba Hosseini

Reputation: 119128

you can remove unwanted characters by adapting the parameters right before passing it into the parser like:

let adaptedParams = params.reduce(into: [String: String]()) { $0[$1.key] = $1.value.joined(separator: ",") }

Upvotes: 1

Related Questions