Monday, March 24th, 2008
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];
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
CFStringEncodingusing 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.