Convert dictionary to query string in swift?

前端 未结 11 848
走了就别回头了
走了就别回头了 2021-01-04 04:37

I have a dictionary as [String:Any].Now i want to convert this dictionary keys & value as key=value&key=value.I have created below extensio

11条回答
  •  日久生厌
    2021-01-04 05:27

    import Foundation
    
        extension URL {
            var queryItemsDictionary: [String: String] {
                var queryItemsDictionary = [String: String]()
    
                // we replace the "+" to space and then encode space to "%20" otherwise after creating URLComponents object
                // it's not possible to distinguish the real percent from the space in the original URL
                let plusEncodedString = self.absoluteString.replacingOccurrences(of: "+", with: "%20")
    
                if let queryItems = URLComponents(string: plusEncodedString)?.queryItems {
                    queryItems.forEach { queryItemsDictionary[$0.name] = $0.value }
                }
                return queryItemsDictionary
            }
        }
    

    That extension will allow you to parse URL where you have both encoded + sign and space with plus, for example:

    https://stackoverflow.com/?q=First+question&email=mail%2B10@mail.com
    

    That extension will parse "q" as "First question" and "email" as "mail+10@mail.com"

提交回复
热议问题