Search code examples
iosswifturlencodeurldecode

Encode url string to Dictionary In my case: Some value have = inside


I'm trying to convert decode to dictionary from the below url encoded string. The normal method of doing so is given below. In my case it is not working. Also i need to remove any character like \u{05}

let params = str.components(separatedBy: "&").map({
    $0.components(separatedBy: "=")
}).reduce(into: [String:String]()) { dict, pair in
    if pair.count == 2 {
        dict[pair[0]] = pair[1]
    }
}

My url encoded string is

"id=sfghsgh=sbfsfhj&name=awsjdk_fs\u{05}"

I'm expecting result as

{ 
"id" = "sfghsgh=sbfsfhj",
"name" = "awsjdk_fs"
}

How it is possible to achive?


Solution

  • Piggyback on URLComponents:

    var components = URLComponents()
    components.query = "id=sfghsgh=sbfsfhj&name=awsjdk_fs"
    
    components.queryItems
    // => Optional([id=sfghsgh=sbfsfhj, name=awsjdk_fs])
    
    let list = components.queryItems?.map { ($0.name, $0.value) } ?? []
    // [("id", Optional("sfghsgh=sbfsfhj")), ("name", Optional("awsjdk_fs"))]
    
    let dict = Dictionary(list, uniquingKeysWith: { a, b in b })
    // ["name": Optional("awsjdk_fs"), "id": Optional("sfghsgh=sbfsfhj")]
    

    If you need a [String: String] rather than [String: String?]:

    let list = components.queryItems?.compactMap { ($0.name, $0.value) as? (String, String) } ?? []
    // [("id", "sfghsgh=sbfsfhj"), ("name", "awsjdk_fs")]
    
    let dict = Dictionary(list, uniquingKeysWith: { a, b in b })
    // ["name": "awsjdk_fs", "id": "sfghsgh=sbfsfhj"]