RKValueTransformers “failed transformation of value to NSDate”

▼魔方 西西 提交于 2019-11-27 16:30:45

Restkit doesn't support this kind of date format out of the box, but you're in luck because it is easy to add new date formats to Restkit. First you need to create a date formatter that works for your incoming dates. I've created a date formatter for the date in your question; If you want, you can test it by plopping this code in your app delegate and checking the logs when you run:

NSString * dateStr = @"September 01, 2014 14:53:30 PDT";

NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setDateFormat:@"MMMM dd, yyyy HH:mm:ss z"];
NSDate *date = [dateFormatter dateFromString:dateStr];

NSDateFormatter *otherFormatter = [NSDateFormatter new];
[otherFormatter setDateStyle:NSDateFormatterFullStyle];
NSLog(@"%@",[otherFormatter stringFromDate:date]);

You should see that the date is correctly converted to an NSDate object and can be printed using any other valid date format. Don't keep this code in your app delegate...this was just to prove to yourself that the date formatter works.

Now that you have the correct date formatter, you just need to add it to RestKit's list of date formatters so that it can properly interpret the date string that comes from your RSS feeds. You should not need to change your data model to an NSString as was suggested in the comments above.

This is pretty simple...during RestKit setup just drop this in:

NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setDateFormat:@"MMMM dd, yyyy HH:mm:ss z"];
[RKObjectMapping addDefaultDateFormatter:dateFormatter];

It has been some time since I added a custom date formatter to RestKit, so if that doesn't work, check the docs to see if the syntax for adding a formatter has changed.

p.s. Be careful to check the time zones when this is implemented and running...I've had issues with that in the past, but I believe the above will work for your use case.

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