Skip to content

Instantly share code, notes, and snippets.

@DanielCardonaRojas
Created October 10, 2019 19:19
Show Gist options
  • Save DanielCardonaRojas/d47e4dbe39bc97c2121ea8d3509c9c32 to your computer and use it in GitHub Desktop.
Save DanielCardonaRojas/d47e4dbe39bc97c2121ea8d3509c9c32 to your computer and use it in GitHub Desktop.
Send codable in notification payload.
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