Search code examples
objective-ccocoa-touchchinese-localeitunes-search-api

Obj-C, encode Simplified Chinese in an iTunes search querystring?


I'm struggling to use the iTunes search API with Simplified Chinese. I've tried a couple of character variations (provided by google translate) along with HTML encoding the characters.

The code below doesn't cause any errors but it doesn't give me any results, unlike English words. I've also tried different Chinese words.

However I'm not sure how to proceed.

NSString *url_string = @"";

NSString *keyword = [@"Chéngfǎ" stringByReplacingOccurrencesOfString: @" " 
   withString: @"%20"];
//NSString *keyword = [@"乘法" stringByReplacingOccurrencesOfString: @" " 
   withString: @"%20"];

url_string = [NSString stringWithFormat: 
    @"https://itunes.apple.com/search?term=%@&country=%@&entity=software", keyword, @"cn"];

NSError *error;
NSData *data = [NSData dataWithContentsOfURL: [NSURL URLWithString: url_string]];

NSMutableArray *json;
if (data != nil)
{
json = [NSJSONSerialization JSONObjectWithData:data options: kNilOptions error: &error];
}

NSDictionary *outer = [json valueForKey: @"results"];

for(NSDictionary *item in outer)
{
   //results
}

Solution

  • I tried to type the URL into browser and I get the results. I think you need to percent encode the chinese characters?

    https://itunes.apple.com/search?term=%E4%B9%98%E6%B3%95&country=cn&entity=software

    You can use iOS function stringByAddingPercentEncodingWithAllowedCharacters.