Created
June 15, 2020 12:24
-
-
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.
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 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