Created
October 10, 2019 19:19
-
-
Save DanielCardonaRojas/d47e4dbe39bc97c2121ea8d3509c9c32 to your computer and use it in GitHub Desktop.
Send codable in notification payload.
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
extension Encodable { | |
var asDictionary: [String: Any]? { | |
guard let data = try? JSONEncoder().encode(self) else { return nil } | |
return (try? JSONSerialization.jsonObject(with: data, options: .allowFragments)).flatMap { $0 as? [String: Any] } | |
} | |
} | |
extension Decodable { | |
static func fromDictionary(from json: Any) -> Self? { | |
guard let jsonData = try? JSONSerialization.data(withJSONObject: json, options: []) else { | |
return nil | |
} | |
return try? JSONDecoder().decode(Self.self, from: jsonData) | |
} | |
} | |
extension Notification { | |
static func fromEntity<T: Codable>(named: String, userInfo: T, object: Any?) -> Notification { | |
let name = Notification.Name(named) | |
let userInfo = userInfo.asDictionary | |
return Notification(name: name, object: object, userInfo: userInfo) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment