5

I need to pass Cyrillic characters as a parameter in a URL in my iPhone app. A sample URL looks like:

http://www.mysite.com/script.php?message=страшная

When I use this URL in my browser, it returns the correct result. However, in my app, the cyrillic is not liked, and I end up getting a "bad url" in the didFailWithError code.

I have tried several encodings in my browser to get around this, but with no luck. Is there a way to actually send the exact URL example above via an iPhone app? The snippet of code I am using is:

selectedWord = @"страшная";
NSString *requestURL = [NSString stringWithFormat:@"http://www.mysite.com/script.php?message=%@", selectedWord];
NSLog (requestURL);
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:requestURL]];

[[NSURLConnection alloc] initWithRequest:request delegate:self];

In the above code, I have hardcoded the cyrillic word in the NSString *selectedWord for debug purposes. In the real application it will be dynamic based on user input.

I have tried a more complex POST, thinking that I could pass the cyrillic as data rather than text, but either I am doing it wrong, or it doesn't work either.

Any example regarding encoding I can try in my browser, then implement in the app would be helpful. I realize that the cyrillic is being rejected in the NSURL, but I was hoping there was a way around it with different code or encoding.

Costique
  • 23,712
  • 4
  • 76
  • 79
user472938
  • 128
  • 2
  • 6

1 Answers1

15

What if you change it to:

encodedSelectedWord = [selectedWord stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *requestURL = [NSString stringWithFormat:@"http://www.mysite.com/script.php?message=%@", encodedSelectedWord];

documentation link

Kris Markel
  • 12,142
  • 3
  • 43
  • 40
  • Thanks Robot K! That worked!I guess I really need to search the documentation more for all the possible encodings. I didn't see that one mentioned where I looked! – user472938 Oct 12 '10 at 13:50
  • It's not easy to find. NSString is a huge class, and some of the methods names are rather confusing. – Kris Markel Oct 12 '10 at 13:54
  • Thank you, it works also for spanish special characters like á, é, í, ó, ú and ñ. – mvasco Oct 26 '14 at 22:10
  • 1
    NSString * encodedString = [@"string to encode" stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]; use this because your method is deprecated – Genevios Jun 24 '18 at 06:16