2

I just learned the hard way that you cannot pass special characters through NSURL. I am in need of a function that will help me pass characters like "&, %, ", ñ" and others via NSURL and NSData.

My code is below. You can see below that I replace the line breaks (\n) and spaces with %20. Is there a function or simple way I can have the types of characters listed above pass through NSURL? Any help would be great! Thank you!

NSString *var1_pre = [myTextView.text stringByReplacingOccurrencesOfString:@" " 
withString:@"%20"];

NSString *var1 = [var1_pre stringByReplacingOccurrencesOfString:@"\n" withString:@"%20"];

NSString *strURL = [NSString stringWithFormat:@"http://www.website.com/page.php?
var1=%@",var1];

NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
user2492064
  • 591
  • 1
  • 8
  • 21
  • [How to do proper URL encoding?](http://stackoverflow.com/questions/12652396/ios-how-to-do-proper-url-encoding) – Hemang Aug 13 '13 at 11:15
  • For more info look on it http://stackoverflow.com/questions/15548495/google-api-gives-error-when-location-entering-in-danish-language-setting-in-ipho – Arpit Kulsreshtha Aug 13 '13 at 11:23

2 Answers2

12

Use

NSString *strUrl=[@"YOURURL" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url=[NSURL URLWithString:strUrl];
iphonic
  • 12,615
  • 7
  • 60
  • 107
  • Thanks, I actually have several variables that I pass (I listed only 1 in my sample code for simplicity sake). How would I edit your answer to handle 3 different variables that need to be passed? – user2492064 Aug 13 '13 at 10:56
  • only pass the variables' values through percentExcapesUsingEncoding type of mehtods. You should not pass those parts of your url where & or = etc are part of the url syntax. Nor should you encode the variable names (although it should not do any harm) but encode all the values only. – Hermann Klecker Aug 13 '13 at 10:59
0
NSString *urlString = [NSString stringWithFormat:@"URL_STRING"];     
NSURL *MyUrl = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

stringByAddingPercentEscapesUsingEncoding. convert Legal URL String.

iPatel
  • 46,010
  • 16
  • 115
  • 137