Couldn't encode Plus character in URL + swift

前端 未结 3 1324
醉酒成梦
醉酒成梦 2021-01-11 20:54

i am using a GET method in which i have to pass a email address in the URL. API expects it to be encoded. I tried with the encoding options but the \'+\' character couldnt b

相关标签:
3条回答
  • 2021-01-11 21:08

    When you use .urlHostAllowed character set '+' is not encoded.

    Add extension to String like below

    public func stringByAddingPercentEncodingToData() -> String? {
        let finalString = self.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed)?.replacingOccurrences(of: "&", with: "%26").replacingOccurrences(of: "+", with: "%2B")
        return finalString
    }
    

    You can do something like this.

    0 讨论(0)
  • 2021-01-11 21:10

    Unfortunately, both CharacterSet.urlHostAllowed and CharacterSet.urlQueryAllowed contains + as allowed. And for historical reason, most web servers treat + as a replacement of whitespace (), so you need to escape +.

    For such purpose, you may need to define your own CharacterSet:

    extension CharacterSet {
        static let rfc3986Unreserved = CharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~")
    }
    
    let emailAddressText = "mano+1@gmail.com"
    
    let encodedEmail = emailAddressText.addingPercentEncoding(withAllowedCharacters:.rfc3986Unreserved)
    
    print(encodedEmail!) //->mano%2B1%40gmail.com
    
    0 讨论(0)
  • 2021-01-11 21:15

    Try this :

    let encodedEmail = emailAddressTxt.text!
    
            var urlString = "http://yyy.xxx.com/User/GetUserDetailsByEmailAddress?EmailAddress=\(encodedEmail)"
            urlString = urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
    

    or

    let encodedEmail = emailAddressTxt.text!

    let urlString = "http://yyy.xxx.com/User/GetUserDetailsByEmailAddress?EmailAddress=\(encodedEmail!)"
    urlString = urlString.addingPercentEncoding(withAllowedCharacters:.urlHostAllowed)
    
    print(escapedString)
    
    0 讨论(0)
提交回复
热议问题