Swift - encode URL

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

If I encode a string like this:

var escapedString = originalString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)

it does

17条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-21 22:45

    Swift 4:

    It depends by the encoding rules followed by your server.

    Apple offer this class method, but it don't report wich kind of RCF protocol it follows.

    var escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
    

    Following this useful tool you should guarantee the encoding of these chars for your parameters:

    • $ (Dollar Sign) becomes %24
    • & (Ampersand) becomes %26
    • + (Plus) becomes %2B
    • , (Comma) becomes %2C
    • : (Colon) becomes %3A
    • ; (Semi-Colon) becomes %3B
    • = (Equals) becomes %3D
    • ? (Question Mark) becomes %3F
    • @ (Commercial A / At) becomes %40

    In other words, speaking about URL encoding, you should following the RFC 1738 protocol.

    And Swift don't cover the encoding of the + char for example, but it works well with these three @ : ? chars.

    So, to correctly encoding each your parameter , the .urlHostAllowed option is not enough, you should add also the special chars as for example:

    encodedParameter = parameter.replacingOccurrences(of: "+", with: "%2B")
    

    Hope this helps someone who become crazy to search these informations.

提交回复
热议问题