I\'m getting this exception when I try to JSON encode NSDate object.I believe NSDate is not compatible for JSON encoding. but I must encode the date.Any solutions?
For our case, we are using Mantle to convert an object to JSON and one of our objects with property NSDate is missing its JSONTransformer
@property (nonatomic) NSDate *expiryDate;
where:
+ (NSValueTransformer *)expiryDateJSONTransformer {
return [MTLValueTransformer transformerUsingForwardBlock:^id(NSString *dateString, BOOL *success, NSError *__autoreleasing *error) {
return [self.dateFormatter dateFromString:dateString];
} reverseBlock:^id(NSDate *date, BOOL *success, NSError *__autoreleasing *error) {
return [self.dateFormatter stringFromDate:date];
}];
}
+ (NSDateFormatter *)dateFormatter {
NSDateFormatter *df = [NSDateFormatter new];
df.dateFormat = @"yyyy-MM-dd";
return df;
}
I am doing something like this in my body params encoder
// handle dates
var _params = [String: Any]()
params.forEach { (key, value) in
if let date = value as? Date {
_params[key] = DateFormatter.iso8601Full.string(from: date)
} else {
_params[key] = value
}
}
return try? JSONSerialization.data(withJSONObject: _params)