Swift - encode URL

后端 未结 17 1904
無奈伤痛
無奈伤痛 2020-11-21 22:20

If I encode a string like this:

var escapedString = originalString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)

it does

17条回答
  •  无人及你
    2020-11-21 22:55

    Had need of this myself, so I wrote a String extension that both allows for URLEncoding strings, as well as the more common end goal, converting a parameter dictionary into "GET" style URL Parameters:

    extension String {
        func URLEncodedString() -> String? {
            var escapedString = self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
            return escapedString
        }
        static func queryStringFromParameters(parameters: Dictionary) -> String? {
            if (parameters.count == 0)
            {
                return nil
            }
            var queryString : String? = nil
            for (key, value) in parameters {
                if let encodedKey = key.URLEncodedString() {
                    if let encodedValue = value.URLEncodedString() {
                        if queryString == nil
                        {
                            queryString = "?"
                        }
                        else
                        {
                            queryString! += "&"
                        }
                        queryString! += encodedKey + "=" + encodedValue
                    }
                }
            }
            return queryString
        }
    }
    

    Enjoy!

提交回复
热议问题