How do I URL encode a string

前端 未结 22 1688
轮回少年
轮回少年 2020-11-22 07:16

I have a URL string (NSString) with spaces and & characters. How do I url encode the entire string (including the & ampersand

22条回答
  •  长情又很酷
    2020-11-22 08:08

    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 the above function from this link: http://useyourloaf.com/blog/how-to-percent-encode-a-url-string/

    You can also use this function with swift extension. Please let me know if there is any issue.

提交回复
热议问题