swift - 如果日期是过去,则 API 排除数据
问题描述
如果嵌套列表“调用”包含过去的属性,我正在尝试从我的 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调用在过滤之前完成,这不太理想,因为这意味着所有数据都是在过滤之前下载的,理想情况下,我希望在下载任何可以指出我正确方向的人之前过滤数据对实现这一目标表示欢迎。
此外,此解决方案仅检查日期是否为今天,而不检查日期是否为将来。
推荐阅读
- loops - Python 3.7 循环无法识别输入数据
- c - 在列表中添加一个元素
- react-static - 错误:为 URL About (src\pages\About.js) 导出 HTML 失败:不变量失败
- java - 如何使用比较器按值对 TreeMap 进行排序
- javascript - JavaScript - 在一行中格式化多个变量输出
- python - 小波变换的两个不同值 (Daubechies D4)
- rust - &mut(拥有值)错误
- python - 使用 lmfit 的 2 组织 3 隔室模型拟合数据
- javascript - 获取用户数据 Gmail API - JS
- android - Android:在 ListView 上搜索