You should use Swift4 Codable protocol to initialise your object from the json returned by the api. You will need to restructure your structure to match the data returned by the api:
struct PushNotificationDetail: Codable, CustomStringConvertible {
let aps: Aps
let type: String
let message: String?
var description: String { return aps.description + " - Type: " + type + " - Message: " + (message ?? "") }
}
struct Aps: Codable, CustomStringConvertible {
let alert: Alert
var description: String { return alert.description }
}
struct Alert: Codable, CustomStringConvertible {
let title: String
let body: String
var description: String { return "Tile: " + title + " - " + "Body: " + body }
}
extension Data {
var string: String { return String(data: self, encoding: .utf8) ?? "" }
}
Playground Testing
let json = """
{"aps":{"alert":{"title":"Payload","body":"Lets map this thing"}},"type":"alert","message":"This is a message"}
"""
if let pnd = try? JSONDecoder().decode(PushNotificationDetail.self, from: Data(json.utf8)) {
print(pnd) // "Tile: Payload - Body: Lets map this thing - Type: alert - Message: This is a message\n"
// lets encode it
if let data = try? JSONEncoder().encode(pnd) {
print(data.string) // "{"aps":{"alert":{"title":"Payload","body":"Lets map this thing"}},"type":"alert","message":"This is a message"}\n"
print(data == Data(json.utf8)) // true
}
}