URLEncoding a string with Objective-C

若如初见. 提交于 2019-11-30 17:48:11

I think the NSAlert is interpreting the % characters as string format specifiers which are being filled with random data. Just NSLog the output and it's fine:

%27Decoded%20data%21%27%2Ffoo.bar%3Abaz

Also, you have a memory leak in your -urlEncoded category method. You create the string using a CF function containing Create so you are responsible for releasing it.

-(NSString *) urlEncoded
{
   CFStringRef urlString = CFURLCreateStringByAddingPercentEscapes(
                                                   NULL,
                                                   (CFStringRef)self,
                                                   NULL,
                                                   (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",
                                                   kCFStringEncodingUTF8 );
    return [(NSString *)urlString autorelease];
}

I've open sourced my URL encoder utility class which intelligently skips the domain and path portion of the URL (to avoid encoding the slashes, etc...) and escape only the percent sequences that are not followed by 2-digit hex codes (to prevent double encoding of percents like this: %20 -> %2520).

It has been tested against over 10,000 URLs and is very robust and performant.

You can learn more about (and download) my implementation here... http://jayfuerstenberg.com/devblog/url-encoding-in-objective-c

Rather than autorelease, which is no longer available when using ARC, create your instance method by passing a string and using CFBridgingRelease:

- (NSString *)urlEncodeWithString: (NSString*)string
{
  CFStringRef urlString = CFURLCreateStringByAddingPercentEscapes(
                                                                  NULL,
                                                                  (CFStringRef)string,
                                                                  NULL,
                                                                  (CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",
                                                                  kCFStringEncodingUTF8 );
  return (NSString *)CFBridgingRelease(urlString);
}

OK turns out it was a nonissue. It was being encoded correctly because I checked the server logs and it seems the request params were encoded.

And for displaying the encoded string in the dialog box correctly, I just replaced all instances of % with %% after the fact.

In my opinion the easiest way is to use convenient method supplied with NSString (NSURLUtilities) category

My implementation:

- (NSString *) urlEncodedString
{
    NSString *result = [self stringByReplacingOccurrencesOfString:@" " withString:@"+"];
    result = [result stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    return result;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!