Convert date format from json data in the model and then pass to controller

旧城冷巷雨未停 提交于 2019-12-25 19:06:14

问题


Here in my model I have a few struct to handle the data from server

struct Articles: Decodable {
var content : [ArticleData]

}

struct ArticleData: Decodable {
var title: String
var date_time: Date
var image: String
}

From the jason, I get a date, it's like that:

 "date_time": 1524842056.035,

First question: I set the type of this type in model Date as you see in ArticleData, it that correct?

Then I read this json in the model something like that:

  guard let json = try? JSONDecoder().decode(Articles.self, from: data!) else {
   completion(.failure(loginError.networkError))
                return
            }

    completion(.success(json.content))

As you can see, I get an array from server json.content that contain title, date_time and image. I want to convert it here in the model and pass everything in completion to the controller. could you help me on that?

Thanks :)


回答1:


you can use type 'String' for your date and then convert it using dateFormatter or, use 'dateDecodingStrategy' function in your decoder. for passing the data you are already doing the correct thing. where ever you call the method you can get the model.



来源:https://stackoverflow.com/questions/57627890/convert-date-format-from-json-data-in-the-model-and-then-pass-to-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!