Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape an NSString to use in NSURL? [closed]

Got this code so far for my send button:

NSString* urlString = [NSString stringWithFormat:@"http://server.com/ios/add.php?user=iPhone+App&message=%@", messageBox.text stringByAddingPercentEscapesUsingEncoding : NSUFT8StringEncoding];
NSURL *add = [NSURL URLWithString:urlString];

However I do get the error "Expected ':'

like image 202
Emil Elkjær Avatar asked Oct 22 '12 15:10

Emil Elkjær


2 Answers

You need to separate the two string construction calls

NSString* urlString = [[NSString stringWithFormat:@"http://server.com/ios/add.php?user=iPhone+App&message=%@", messageBox.text] stringByAddingPercentEscapesUsingEncoding : NSUTF8StringEncoding];
NSURL *add = [NSURL URLWithString:urlString];
like image 118
Dan F Avatar answered Sep 30 '22 19:09

Dan F


The proper way is not to escape the entire URL. You should only escape individual parameter values.

NSString* urlString = [NSString stringWithFormat:@"http://server.com/ios/add.php?user=iPhone+App&message=%@", [messageBox.text stringByAddingPercentEscapesUsingEncoding : NSUFT8StringEncoding]];

Better yet, for readability and easier debugging, do this:

NSString *escapedText = [messageBox.text stringByAddingPercentEscapesUsingEncoding:NSUFT8StringEncoding];
NSString* urlString = [NSString stringWithFormat:@"http://server.com/ios/add.php?user=iPhone+App&message=%@", escapedText];
like image 40
rmaddy Avatar answered Sep 30 '22 19:09

rmaddy