carson-katri / swift-request

Declarative HTTP networking, designed for SwiftUI
MIT License
730 stars 41 forks source link

Custom decoder for date #16

Closed staticdreams closed 4 years ago

staticdreams commented 4 years ago

How would I go about decoding custom data, such as custom formatted dates? Do we have access to JSONDecoder so we can do something like this: ?

struct Event: Codable {
    var name: String?
    var createdDate: Date?
}

extension DateFormatter {
    static let dateFormatter: DateFormatter = {
     let formatter = DateFormatter()
     formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
      return formatter
    }()
}

let decoder: JSONDecoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(.dateFormatter)
carson-katri commented 4 years ago

You can use onData and manually perform Json decoding:

Request {
    ...
}
.onData { data in
    let decoder = JSONDecoder()
    ...
    let events = try? decoder.decode([Event].self, from: data)
}
staticdreams commented 4 years ago

Thanks I will try that. Sorry for stupid questions, I couldn't find an example in the docs :)

carson-katri commented 4 years ago

No problem! Let me know if you have any other questions.