Swift - encode URL

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

If I encode a string like this:

var escapedString = originalString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)

it does

17条回答
  •  北恋
    北恋 (楼主)
    2020-11-21 22:52

    Swift 4 & 5

    To encode a parameter in URL I find using .alphanumerics character set the easiest option:

    let encoded = parameter.addingPercentEncoding(withAllowedCharacters: .alphanumerics)
    let url = "http://www.example.com/?name=\(encoded!)"
    

    Using any of the standard Character Sets for URL Encoding (like URLQueryAllowedCharacterSet or URLHostAllowedCharacterSet) won't work, because they do not exclude = or & characters.

    Note that by using .alphanumerics it will encode some characters that do not need to be encoded (like -, ., _ or ~ -– see 2.3. Unreserved characters in RFC 3986). I find using .alphanumerics simpler than constructing a custom character set and do not mind some additional characters to be encoded. If that bothers you, construct a custom character set as is described in How to percent encode a URL String, like for example:

    var allowed = CharacterSet.alphanumerics
    allowed.insert(charactersIn: "-._~") // as per RFC 3986
    let encoded = parameter.addingPercentEncoding(withAllowedCharacters: allowed)
    let url = "http://www.example.com/?name=\(encoded!)"
    

    Warning: The encoded parameter is force unwrapped. For invalid unicode string it might crash. See Why is the return value of String.addingPercentEncoding() optional?. Instead of force unwrapping encoded! you can use encoded ?? "" or use if let encoded = ....

提交回复
热议问题