Skip to content

Instantly share code, notes, and snippets.

@alecdoconnor
Created March 8, 2019 15:18
Show Gist options
  • Save alecdoconnor/e1d9801ae63743f9f9f7fb130c58e7c1 to your computer and use it in GitHub Desktop.
Save alecdoconnor/e1d9801ae63743f9f9f7fb130c58e7c1 to your computer and use it in GitHub Desktop.
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
}
}
@alecdoconnor
Copy link
Author

alecdoconnor commented Mar 8, 2019

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)

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