Navigation

NSURLResponse’s textEncodingName

Monday, March 24th, 2008

Really?

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:MY_AWESOME_URL];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSStringEncoding responseEncoding = CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding((CFStringRef)[response textEncodingName]));
NSString *responseString = [[[NSString alloc] initWithData:responseData encoding:responseEncoding] autorelease];

Is CFStringConvertEncodingToNSStringEncoding(CFStringConvertIANACharSetNameToEncoding((CFStringRef)[response textEncodingName])) really necessary? For the first time I’m doing some reasonably heavy lifting with NSURLConnection, and I remember why I’ve been avoiding diving in too deeply (so far I’ve managed to either use Small Sockets, +stringWithContentsOfURL:, or not use Cocoa at all for my network-enabled projects).

According to the documentation:

Clients can convert [textEncodingName] to an NSStringEncoding or a CFStringEncoding using the methods and functions available in the appropriate framework.

However, the best way I’ve seen for getting to an NSStringEncoding is the above code, which wraps an NSString cast in two horribly long function calls. Why wasn’t this provided as a class method on NSURLResponse, or even better, have NSURLResponse return an NSStringEncoding, flat out.

In situations like this in the past, I’ve used PyObjC and Python’s excellent networking APIs to do heavy lifting. Unfortunately, neither Python nor PyObjC are available on a certain small device that runs an operating system similar to Mac OS X.

Filed as Radar #5817106.

Comments

  1. Jordy/Jediknil replied on April 4th, 2008:

    Hey, remember this is Objective-C! Just make a category on NSURLResponse, ‑textStringEncoding or something.

    While you’re at it, you might as well add a method for getting a string result instead of a data result, basically wrapping the whole process once and for all. I mean, if you know it’s string data anyway…