I have 2 type date from api. I need to decode together. But I didn't find any solution. I need to add "yyyy-MM-dd'T'HH:mm:ssZ"
format in this code. How can I do this?
func run<T: Decodable>(_ request: URLRequest, _ decoder: JSONDecoder = JSONDecoder()) -> AnyPublisher<Response<T>, Error> {
return URLSession.shared
.dataTaskPublisher(for: request)
.receive(on: DispatchQueue.main)
.tryMap { result -> Response<T> in
self.dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
decoder.dateDecodingStrategy = .formatted(self.dateFormatter)
let value = try decoder.decode(T.self, from: result.data)
return Response(value: value, response: result.response)
}
.eraseToAnyPublisher()
}
Another approach is a custom dateDecodingStrategy
with ISO8601DateFormatter
which is able to specify the date format depending on the given string
func run<T: Decodable>(_ request: URLRequest, _ decoder: JSONDecoder = JSONDecoder()) -> AnyPublisher<Response<T>, Error> {
return URLSession.shared
.dataTaskPublisher(for: request)
.receive(on: DispatchQueue.main)
.tryMap { result -> Response<T> in
decoder.dateDecodingStrategy = .custom { decoder -> Date in
let container = try decoder.singleValueContainer()
let dateFormatter = ISO8601DateFormatter()
let dateString = try container.decode(String.self)
if !dateString.hasSuffix("Z") {
dateFormatter.formatOptions.remove(.withTimeZone)
}
if let isoDate = dateFormatter.date(from: dateString) {
return isoDate
} else {
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Wrong Date Format")
}
}
let value = try decoder.decode(T.self, from: result.data)
return Response(value: value, response: result.response)
}
.eraseToAnyPublisher()
}
You can implement custom decoding behavior by implementing init(from decoder: Decoder)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.