API如果日期在过去,则排除数据



如果嵌套列表"calls"包含过去的属性,我将尝试从API响应中排除数据

在响应中包含此数据:

[
{
"addressLineOne":"Test",
"addressLineTwo":"Test2",
"calls":{
"dateTime":1597932000, // a date in the future
},
]

排除此数据:

[
{
"addressLineOne":"Test",
"addressLineTwo":"Test2",
"calls":{
"dateTime":1596193200 // a date in the past
},
]

我正在使用JSON解码器进行api调用:

class Service {
static let shared = Service()
let BASE_URL = "url.com/JsonData"
func fetchClient(completion: @escaping ([Client]) -> ()) {
guard let url = URL(string: BASE_URL) else { return }
URLSession.shared.dataTask(with: url) { (data, response, error) in
// handle error
if let error = error {
print("Failed to fetch data with error: ", error.localizedDescription)
return
}
guard let data = data else {return}
do {
let clients = try JSONDecoder().decode([Client].self, from: data)
completion(clients)

} catch let error {
print("Failed to create JSON with error: ", error.localizedDescription)
}
}.resume()
}
}

任何方向都将不胜感激

通过添加过滤器并使用内置的Calendar函数检查日期来解决此问题:

class Service {
static let shared = Service()
let BASE_URL = "url.com/JsonData"
let calendar = Calendar.current

func fetchClient(completion: @escaping ([Client]) -> ()) {
guard let url = URL(string: BASE_URL) else { return }
URLSession.shared.dataTask(with: url) { (data, response, error) in
// handle error
if let error = error {
print("Failed to fetch data with error: ", error.localizedDescription)
return
}
guard let data = data else {return}
do {
let myDecoder = JSONDecoder()
myDecoder.dateDecodingStrategy = .secondsSince1970 // formats date
let clients = try myDecoder.decode([Client].self, from: data)
completion(clients.filter { self.calendar.isDateInToday($0.calls.dateTime) // filters dates upon completion
}) 

} catch let error {
print("Failed to create JSON with error: ", error.localizedDescription)
}
}.resume()
}
}

在我的解决方案中,API调用在过滤之前完成,这是不太重要的,因为这意味着所有数据都是在进行过滤之前下载的,理想情况下,我希望在下载之前对数据进行过滤。欢迎任何能为我指明实现这一目标的正确方向的人。

此外,此解决方案只检查日期是否为今天,而不检查日期是否在将来。

相关内容

  • 没有找到相关文章

最新更新