Parsing unix timestamp with RestKit in iOS
-
27-10-2019 - |
Question
For an iOS app I am working on with RestKit I need to parse a unix timestamp changed = "1325470840" into an NSDate. I know that I can manually do this with
[NSDate dateWithTimeIntervalSince1970:1325470840]
But I am using RestKits core data integration and this is handled behind the scenes using date formatters, such as below.
[RKObjectMapping addDefaultDateFormatterForString:@"E MMM d HH:mm:ss Z y" inTimeZone:nil];
Does anyone know how to create a date formatter to parse a unix timestamp? Or how I could go about parsing this with RestKit?
Solution
Well, I found my problem. RestKit fixed this in issue #141, but the server I am contacting returns a string instead of an expected number so the auto parser does not know what to do with it. I created a request to add a NSString > NSNumber > NSDate parser to RestKit (#503). In the meantime I am manually updating the string to a number as shown below before the actual parsing happens.
- (void)objectLoader:(RKObjectLoader *)loader willMapData:(inout id *)mappableData
{
NSArray *dateKeys = [NSArray arrayWithObjects:@"changed", nil];
NSMutableArray *reformattedData = [NSMutableArray arrayWithCapacity:[*mappableData count]];
for(id dict in [NSArray arrayWithArray:(NSArray*)*mappableData]) {
NSMutableDictionary* newDict = [dict mutableCopy];
for(NSString *dateKey in dateKeys) {
NSNumber *num = [NSNumber numberWithInt:[[newDict valueForKey:dateKey] intValue]];
[newDict setValue:num forKey:dateKey];
}
[reformattedData addObject:newDict];
}
*mappableData = reformattedData;
}