I tried to pass these characters to server, for example *()$
I have coded the NSUrl this way:
NSString *partialURL = [NSString stringWithFormat:@"/%@", commentBody];
NSString *fullURL = [NSString stringWithFormat:@"%@%@", CONST_URL, partialURL];
NSString *encStr = [fullURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:encStr];
But then, the commentBody
passed in the url still has *()$
things and not encoded into utf8.
What is the correct way to do it? Thanks!
NSString * test = (NSString *) CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)validUrl,
NULL,
(CFStringRef)@";/?:@&=$+{}<>,",
kCFStringEncodingUTF8);
UPDATE
Hi @Rendy. Sorry for the quickie reply yesterday. I only had time to past a 1-liner before jumping off and had hoped it would be enough for you to correct the issue you were having.
You always want to encode the parameters of the URL. IF you have a URL that is a parameter to another URL or embedded in some XML; you'll want to encode the entire url (which means parameters get double-encoded - because you take a "valid" URL and escape it so it becomes a valid parameter in another URL (ie, :
and &
get escaped, so parameters don't mix together.)
If you like, you can add additional chars to the string below and they'll be replaced with percent-encoded values. I believe the string below already has you covered for the invalid values.
Here's a category on NSString
:
@implementation NSString (encode)
+ (NSString*)stringEncodedAsUrlParameter:(NSString *)string
{
NSString *newString = NSMakeCollectable(
[(NSString *)CFURLCreateStringByAddingPercentEscapes(
kCFAllocatorDefault,
(CFStringRef)string,
NULL, /* charactersToLeaveUnescaped */
CFSTR(":/?#[]@!$ &'()*+,;=\"<>%{}|\\^~`"),
kCFStringEncodingUTF8
) autorelease]
);
if (newString) {
return newString;
}
return @"";
}
- (NSString*)stringByEncodingAsUrlParameter
{
return [NSString stringEncodedAsUrlParameter:self];
}
@end
Call it like this:
NSString * escapedParameters = [NSString stringEncodedAsUrlParameter:unescapedParameters];
Or:
NSString * escapedParameters = [unescapedParameters stringByEncodingAsUrlParameter];
Then add your properly escaped parameters to the end of your URL. If you encode the whole URL, you'll encode the "http://" portion and it won't work.
I originally copied the above from ASIHttpRequest, but any bugs added are mine.
Hope that helps! Best of luck!!