首页 > 解决方案 > 如果日期是过去,则 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()
    }
}

任何方向将不胜感激

标签: swift

解决方案


设法通过添加过滤器并使用内置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调用在过滤之前完成,这不太理想,因为这意味着所有数据都是在过滤之前下载的,理想情况下,我希望在下载任何可以指出我正确方向的人之前过滤数据对实现这一目标表示欢迎。

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


推荐阅读