views:

65

answers:

2

In my program, I'm allowing the user to input some words into a textfield. Then my program will use these words to form a html string. The string will then be used in NSURL so I can connect to the website.

This method works great for english words. But when I input some chinese (or korean) in there, I does not work. Thus I believe that I need to convert the inputed data before passing it to NSURL. However I could not find a way to do this. Here's an example of how my code looks like.

NSString *searchedString = theSearchBar.text;

NSString *urlToBeSearched = [[NSString alloc] 
     initWithFormat:@"http://www.awebsite.com/search/%@", 
     searchedString];
NSURLRequest *urlRequest = [[NSURLRequest alloc] 
    initWithURL:[NSURL URLWithString:urlToBeSearched]
    cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:50];
NSURLConnection *tempCon =[[NSURLConnection alloc] initWithRequest:urlRequest
             delegate:self];

Then of course releasing them later.

For example, when searchedString = 你好, the urlLink will be http://www.awebsite.com/search/你好. NSURLConnection doesn't like that and will give me "Bad Url" error. However, if the urlLink is "%E4%BD%A0%E5%A5%BD" it will give me the correct link.

A: 

Did you try encoding your search-string?

[NSString stringByAddingPercentEscapesUsingEncoding:/encoding-of-choice/];

Not sure what encoding you would use for chinese characters though.

Gubb
A: 

The set of characters allowed in a URI is pretty much limited to a subset of US-ASCII (see RFC2396). That means your Chinese characters must be percent escaped in the URI. The documentation for NSURL +URLWithString: says the string must conform to the RFC so you need to percent escape the string before calling that method.

Fortunately, NSString has a method that will allow you to do that called -stringByAddingPercentEscapesUsingEncoding:. You still need to choose a suitable encoding and which one you choose depends on how the server decodes the URL string. The easiest option is probably to use UTF-8 at both ends. You need to do something like:

NSString* searchedString = [theSearchBar.text stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
NSString* urlToBeSearched = [NSString stringWithFormat:@"http://www.awebsite.com/search/%@", searchedString];

// everything else the same, except you don't need to release urlToBeSearched
JeremyP
Thank you so much. Works great.
Draco
One more question. How do I decode searchedString back into Chinese again?
Draco
You'll need to reverse the actions. On your server, you should chop the front off so you only have the bit after "search/" then you need to reverse the URL encoding. How you do this depends on the language your server side is written in.
JeremyP