Created
October 23, 2019 16:02
-
-
Save hishma/5ebf5d3557a24d4280b5282a55c5e1b8 to your computer and use it in GitHub Desktop.
Percent encode a URL String
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Shamelessly ripped off from: https://useyourloaf.com/blog/how-to-percent-encode-a-url-string/