Swift - encode URL

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

If I encode a string like this:

var escapedString = originalString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)

it does

17条回答
  •  终归单人心
    2020-11-21 23:02

    This one is working for me.

    func stringByAddingPercentEncodingForFormData(plusForSpace: Bool=false) -> String? {
    
        let unreserved = "*-._"
        let allowed = NSMutableCharacterSet.alphanumericCharacterSet()
        allowed.addCharactersInString(unreserved)
    
        if plusForSpace {
            allowed.addCharactersInString(" ")
        }
    
        var encoded = stringByAddingPercentEncodingWithAllowedCharacters(allowed)
    
        if plusForSpace {
            encoded = encoded?.stringByReplacingOccurrencesOfString(" ", withString: "+")
        }
        return encoded
    }
    

    I found above function from this link: http://useyourloaf.com/blog/how-to-percent-encode-a-url-string/.

提交回复
热议问题