Skip to content

Instantly share code, notes, and snippets.

@hishma
Created October 23, 2019 16:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hishma/5ebf5d3557a24d4280b5282a55c5e1b8 to your computer and use it in GitHub Desktop.
Save hishma/5ebf5d3557a24d4280b5282a55c5e1b8 to your computer and use it in GitHub Desktop.
Percent encode a URL String
import Foundation
extension String {
public func addingPercentEncodingForRFC3986() -> String? {
let unreserved = "-._~/?"
let allowed = NSMutableCharacterSet.alphanumeric()
allowed.addCharacters(in: unreserved)
return self.addingPercentEncoding(withAllowedCharacters: allowed as CharacterSet)
}
public func addingPercentEncodingForFormData(plusForSpace: Bool=false) -> String? {
let unreserved = "*-._"
let allowed = NSMutableCharacterSet.alphanumeric()
allowed.addCharacters(in: unreserved)
if plusForSpace {
allowed.addCharacters(in: " ")
}
var encoded = self.addingPercentEncoding(withAllowedCharacters: allowed as CharacterSet)
if plusForSpace {
encoded = encoded?.replacingOccurrences(of: " ", with: "+")
}
return encoded
}
}
@hishma
Copy link
Author

hishma commented Oct 23, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment