Converting encodingName to NSStringEncoding
Converting encodingName to NSStringEncoding
- Subject: Converting encodingName to NSStringEncoding
- From: Patrick Machielse <email@hidden>
- Date: Fri, 09 Jan 2004 13:30:38 +0100
I am using an NSURLConnection and want to convert the returned NSData to an
NSString (I know that the data is text). To do this I need to know the
NSStringEncoding of the data. NSURLResponse gives me the 'textEncodingName',
which is the exact string passed by the server. This string must be queried
to establishe the appropriate encoding. So far I've come up with the
following solution.
{
// some initialisation of variables and setup
// ...
NSData *d = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
NSString *ename = [response textEncodingName];
NSStringEncoding enc = [self encodingForEncodingName:ename];
NSString *reply = [[NSString alloc] initWithData:d encoding:enc];
return [reply autorelease];
}
- (NSStringEncoding)encodingForEncodingName:(NSString *)name
{
const NSStringEncoding *encs = [NSString availableStringEncodings];
while ( *encs++ ) {
NSString *ln = [NSString localizedNameOfStringEncoding:*encs ];
unsigned opt = NSCaseInsensitiveSearch;
NSRange fnd = [ln rangeOfString: name options:opt];
if ( found.location != NSNotFound )
return *encs;
}
return NSUTF8StringEncoding;
}
This works insofar that the server string 'utf-8' gets matched to
NSUTF8StringEncoding (by finding it, not by returning the default!), but
this doesn't seem to be a very robust solution.
I have two questions:
* is there a better way to match textEncodingName (are these MIME
types?) to NSStringEncoding. Has anyone solved this before, have I
overlooked an obvious solution?
* is NSUTF8StringEncoding a safe default encoding to return or is
there a better choice?
I'm not an expert in text encoding and conversion (). It seems Carbon has
more functionality in this respect?
t.i.a.
Patrick
--
Hieper Software
w: www.hieper.nl
e: email@hidden
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.