Created
March 8, 2019 15:18
-
-
Save alecdoconnor/e1d9801ae63743f9f9f7fb130c58e7c1 to your computer and use it in GitHub Desktop.
This file contains 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
extension URL { | |
/// Initializes with a String and can provide automatic URL encoding | |
/// | |
/// Returns nil if a URL cannot be formed with the string (for example, if the string contains characters that are illegal in a URL that could not be encoded, or is an empty string). | |
init?(_ string: String, provideURLEncoding: Bool) { | |
guard provideURLEncoding else { | |
guard let url = URL(string: string) else { return nil } | |
self = url | |
return | |
} | |
guard let safeString = string.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else { return nil } | |
guard let url = URL(string: safeString) else { return nil} | |
self = url | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The purpose of this is to automatically add percent encoding to possibly invalid URLs coming from dynamic sources such as a public/private API. Some URL strings in a JSON response (for example) may have spaces or other invalid characters. This will autocorrect that with percent URL encoding.
// Without URL Encoding
print("Without: (String(describing: URL("", provideURLEncoding: false)))")
print("Without: (String(describing: URL("https://apple.com/", provideURLEncoding: false)))")
print("Without: (String(describing: URL("https://apple.com/this is an apple.html", provideURLEncoding: false)))\n")
// With URL Encoding
print("With: (String(describing: URL("", provideURLEncoding: true)))")
print("With: (String(describing: URL("https://apple.com/", provideURLEncoding: true)))")
print("With: (String(describing: URL("https://apple.com/this is an apple.html", provideURLEncoding: true)))")
--------------------------Prints--------------------------
Without: nil
Without: Optional(https://apple.com/)
Without: nil
With: nil
With: Optional(https://apple.com/)
With: Optional(https://apple.com/this%20is%20an%20apple.html)