Skip to content

Instantly share code, notes, and snippets.

@stleamist
Created June 15, 2020 12:24
Show Gist options
  • Save stleamist/378016cd91cc57f1279e86d7be96dc5f to your computer and use it in GitHub Desktop.
Save stleamist/378016cd91cc57f1279e86d7be96dc5f to your computer and use it in GitHub Desktop.
A KeyedDecodingContainer extension that adds percent encoding to Unicode URL during Codable decoding process.
import Foundation
extension KeyedDecodingContainer {
func decode(_ type: URL.Type, forKey key: Key) throws -> URL {
do {
return try URL(from: superDecoder())
} catch (let error) {
guard
let urlString = try? decode(String.self, forKey: key),
let encodedURLString = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
let encodedURL = URL(string: encodedURLString) else {
throw error
}
return encodedURL
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment