IOS automatically processes Http Request Response content character encoding
Let's take a look at how to access the "web service" without considering the security link issue for the moment. In this example, I want to access the RSS seeds of my blog in a secure way.
Lets first look at how to access our "web service" without the security overhead. In this example I want to access the RSS feed of my blog in a secure fashion.
// our secure service :-)NSURL *server = [NSURL URLWithString:@http://www.cocoanetics.com/feed/];NSURLRequest *request = [NSURLRequest requestWithURL:server]; // use synchronous convenience methodNSURLResponse *response = nil;NSError *error = nil;NSData *returnedData = [NSURLConnection sendSynchronousRequest:requestreturningResponse:&responseerror:&error];if (!returnedData){NSLog(@Error retrieving data, %@, [error localizedDescription]);return NO;} // get the correct text encoding// http://stackoverflow.com/questions/1409537/nsdata-to-nsstring-converstion-problemCFStringEncoding cfEncoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)[response textEncodingName]);NSStringEncoding encoding = CFStringConvertEncodingToNSStringEncoding(cfEncoding); // outputNSString *xml = [[[NSString alloc] initWithData:returnedData encoding:encoding]autorelease];NSLog(@%@, xml); |
In this way, we get the rss xml of my site. Here is a pretty trick. We don't use the hard-coded UTF8 method. We get the appropriate encoding from the response. This is a good habit, and you should adopt it in any situation.
We get the xml of my website RSS through this. there is another nity trick in this, instead of hard coding UTF8 we actually get the appropriate encoding straight from the response. this is a good habbit so you shoshould adopt that in any case.