Use TTURLXMLResponse with server that send you the wrong encoding
24
Jun
2010
That took long. I am parsing RSS, but _one_ particular feed would not parse, the console screamed “NSXMLParserErrorDomain error 9″.
So some stuff in encoding was weird. I replicated the feed on my server, voila, worked like a charm. http://beta.feedvalidator.org finally brought some light into the issue: “Your feed appears to be encoded as “UTF-8″, but your server is reporting “iso-8859-1″”
Okay. So the server fucked up. But we can’t change that, so let’s make our parser more robust. I am using TTURLXMLResponse (see their TTTwitter example on github)
So let’s override that! See the middle part for my change/hack/improvement. (Call it whatever you want)
@implementation VIURLXMLResponse
///////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark TTURLResponse
// overridden from TTURLResponse to hack around voest rss feed!
- (NSError*)request
:(TTURLRequest
*)request processResponse
:(NSHTTPURLResponse*)response
data
:(id)data
{
// This response is designed for NSData objects, so if we get anything else it's probably a
// mistake.
TTDASSERT
([data isKindOfClass
:[NSData class
]]);
TTDASSERT
(nil == _rootObject
);
if ([data isKindOfClass
:[NSData class
]]) {
NSString *utf8Response
= [[[NSString alloc
] initWithData
:data encoding
: NSUTF8StringEncoding
] autorelease
];
// oh ooh. server sent us data in ISO-8859-1? [hack around standards]
// http://stackoverflow.com/questions/1207867/nsxmlparser-rss-issue-nsxmlparserinvalidcharactererror
if (!utf8Response
) {
NSString *dataString
= [[[NSString alloc
] initWithData
:data encoding
:NSASCIIStringEncoding
] autorelease
];
data
= [dataString dataUsingEncoding
:NSUTF8StringEncoding allowLossyConversion
:YES];
}
TTDCONDITIONLOG
(TTDFLAG_XMLPARSER,
@"Data: %@",
[[[NSString alloc
] initWithData
:data encoding
: NSUTF8StringEncoding
] autorelease
]);
TTXMLParser
* parser
= [[TTXMLParser alloc
] initWithData
:data
];
parser.delegate
= self;
parser.treatDuplicateKeysAsArrayItems
= self.isRssFeed;
[parser parse
];
_rootObject
= [parser.rootObject retain
];
TT_RELEASE_SAFELY
(parser
);
}
return nil;
}
@end
Related posts:
- Add Facebook Like Button with Facebook Connect iPhone SDK
- Detect if an iPhone is jailbroken
- NSDateFormatter and +00:00 parsing
- Multithreading with Core Data
- [NSString description] via reflection
2 Responses to Use TTURLXMLResponse with server that send you the wrong encoding
christian
July 28th, 2010 at 12:52 pm
hi , i have same problem, but dont use tturlxmlresponse?
I use the standart NXMLParser
Do you know what and where to fix there to get it run?
I could even provide my parser should it help.
thx
chris
Tassi
August 13th, 2010 at 7:06 pm
schöne Seite