Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift and ObjectMapper: NSDate with min value

I'm using ObjectMapper to cast json into objects. My problem is that the NSDate property is not being mapped correctly. Here is the json:

{
   "Id":4775,
   "Cor":{
      "Id":2,
      "Nome":"Amarelo",
      "HTMLCode":"FFFB00"
   },
   "Data":"2016-07-25T09:35:00",
   "Texto":"test test test",
   "Kilometro":547.0
}

And here is my mappable class

class RoadWarning : Mappable {

    var id: Int?
    var color: RoadWarningColor?
    var date: NSDate?
    var text: String?
    var kilometer: Float?

    required init?(_ map: Map){

    }

    func mapping(map: Map) {
        id <- map["Id"]
        color <- map["Cor"]
        text <- map["Texto"]
        kilometer <- map["Kilometro"]
        date    <- (map["Data"], DateTransform())
    }
}

The problem is that the date property is always 1970-01-01. I can't see yet what I am missing. Can you see what is wrong in this mapping?

Thanks

like image 666
André Luiz Avatar asked Jul 29 '16 22:07

André Luiz


1 Answers

You could just create a TransformType class allowing a dateFormat as parameter:

//  DateFormatTransform.swift

    import Foundation
    import ObjectMapper
    public class DateFormatTransform: TransformType {
        public typealias Object = NSDate
        public typealias JSON = String


    var dateFormat = NSDateFormatter(dateFormat: "yyyy-MM-dd HH:mm:ss")

    convenience init(dateFormat: String) {
        self.init()
        self.dateFormat = NSDateFormatter(dateFormat: dateFormat)
    }

    public func transformFromJSON(value: AnyObject?) -> Object? {
        if let dateString = value as? String {
            return self.dateFormat.dateFromString(dateString)
        }
        return nil
    }
    public func transformToJSON(value: NSDate?) -> JSON? {
        if let date = value {
            return self.dateFormat.stringFromDate(date)
        }
        return nil
    }
}

And use it like this:

func mapping(map: Map) {
    id <- map["Id"]
    color <- map["Cor"]
    text <- map["Texto"]
    kilometer <- map["Kilometro"]
    date    <- (map["Data"], DateFormatTransform(dateFormat: "yyyy-MM-dd"))
}
like image 100
RodolfoAntonici Avatar answered Dec 09 '22 13:12

RodolfoAntonici