Cocoa Fundamentals Category 的例子--更好用的URL encoding方法

如果你在做基于RESTFul的应用,你肯定需要对传递的参数进行编码。比如你要传递信息是:

China,Beijing,Haidian
经过URL编码后,这个字串成了

China%20Beijing%20%Haidian

在iOS中你可以通过如下NSString的方法轻松实现URL编码

stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding

相应的,你可以通过下面的方法还原字串:

stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding
下面是个完整的例子:

NSString *rawText = @"One Broadway, Cambridge, MA";
 
NSString *encodedText = [rawText stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"Encoded text: %@", encodedText);
NSString *decodedText = [encodedText stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"Original text: %@", decodedText);

输出是:

Encoded text: One%20Broadway,%20Cambridge,%20MA
Original text: One Broadway, Cambridge, MA
截至到现在,一切都很美好,NSString可以很好的工作。但是stringByAddingPercentEscapesUsingEncoding不能处理iOs的保留字比如&和/.

看看这个例子:

NSString *rawText = @"Bed Bath & Beyond - URL=http://www.bedbathandbeyond.com/";
 
NSString *encodedText = [rawText stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"Encoded text: %@", encodedText);
NSString *decodedText = [encodedText stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"Original text: %@", decodedText);

输出是:

Bed%20Bath%20&%20Beyond%20-%20URL=http://www.bedbathandbeyond.com/
Original text: Bed Bath & Beyond – URL=http://www.bedbathandbeyond.com/

注意:&和/没有被编码。

当然这种小问题肯定有解决方案,我们看看google是怎么做的。先上源码

#import "GTMNSString+URLArguments.h"
#import "GTMGarbageCollection.h"

@implementation NSString (GTMNSStringURLArgumentsAdditions)

- (NSString*)gtm_stringByEscapingForURLArgument {
  // Encode all the reserved characters, per RFC 3986
  // (<http://www.ietf.org/rfc/rfc3986.txt>)
  CFStringRef escaped = 
    CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                            (CFStringRef)self,
                                            NULL,
                                            (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                            kCFStringEncodingUTF8);
  return GTMCFAutorelease(escaped);
}

- (NSString*)gtm_stringByUnescapingFromURLArgument {
  NSMutableString *resultString = [NSMutableString stringWithString:self];
  [resultString replaceOccurrencesOfString:@"+"
                                withString:@" "
                                   options:NSLiteralSearch
                                     range:NSMakeRange(0, [resultString length])];
  return [resultString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}

@end


眼熟么这句NSString (GTMNSStringURLArgumentsAdditions),这不就是用Category给NString添加了一个新的方法么。

如果你把这个文件加入你的工程,好了现在,你的NSString类的实例和子类实例就已经有了支持rfc3968标准的编码和解码能力了。cool吧。

Google源码链接地址


你可能感兴趣的:(Cocoa Fundamentals Category 的例子--更好用的URL encoding方法)