I am currently trying to put together an URL where I specify some GET parameters. But I want to use japanese or other characters too in this URL.
Is there a way to convert a NSString to a string containing the HTML entities for the ‘special’ characters in my NSString?
I am currently using the following code, which seems to work, except for ‘special characters’ like chinese and japanese:
NSString* url = @'/translate_a/t?client=t&sl=auto&tl='; url = [url stringByAppendingString:destinationLanguage]; url = [url stringByAppendingString:@'&text=']; url = [url stringByAppendingString:text]; NSURL* nsurl = [[NSURL alloc] initWithScheme:@'http' host:@'translate.google.com' path:url]; NSError* error; NSString* returnValue = [[NSString alloc] initWithContentsOfURL:nsurl encoding:NSUTF8StringEncoding error:&error];
To properly URL encode your parameters, you need to convert each name and value to UTF-8, then URL encode each name and value separately, then join names with values using ‘=’ and name-value pairs using ‘&’.
I generally find it easier to put all the parameters in an NSDictionary, then build the query string from the dictionary. Here’s a category that I use for doing that:
The method build an array of name-value pairs called
partsby URL encoding each key and value, then joining them together with ‘=’. Then the parts in thepartsarray are joined together with ‘&’ characters.So for your example: