0

我有这个 URL: http: //google.com并使用它进行 urlencode:

NSArray *escapeChars = [NSArray arrayWithObjects:@";" , @"/" , @"?" , @":" ,
                        @"@" , @"&" , @"=" , @"+" ,
                        @"$" , @"," , @"[" , @"]",
                        @"#", @"!", @"'", @"(",
                        @")", @"*", nil];
NSArray *replaceChars = [NSArray arrayWithObjects:@"%3B" , @"%2F" , @"%3F" ,
                         @"%3A" , @"%40" , @"%26" ,
                         @"%3D" , @"%2B" , @"%24" ,
                         @"%2C" , @"%5B" , @"%5D",
                         @"%23", @"%21", @"%27",
                         @"%28", @"%29", @"%2A", nil];
int len = [escapeChars count];
NSMutableString *temp = url;
int i;
for(i = 0; i < len; i++)
{
    [temp replaceOccurrencesOfString: [escapeChars objectAtIndex:i] withString:[replaceChars objectAtIndex:i] options:NSLiteralSearch range:NSMakeRange(0, [temp length])];
}
return temp;

这是我得到的编码字符串:http0X1.D49C41C5D49CP-5700.0000000.000000google.com

怎么会这样?

4

1 回答 1

1

这是 URL 编码的类别:

NSString+URLEncoding.h

#import <Foundation/Foundation.h>

@interface NSString (URLEncoding)
- (NSString *)urlEncodeUsingEncoding:(NSStringEncoding)encoding;
@end

NSString+URLEncoding.m

#import "NSString+URLEncoding.h"

@implementation NSString (URLEncoding)

- (NSString *)urlEncodeUsingEncoding:(NSStringEncoding)encoding {
return (__bridge NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
                                                           (CFStringRef)self,
                                                           NULL,
                                                           (CFStringRef)@"!*'\"();:@&=+$,/?%#[]%  ",
                                                           CFStringConvertNSStringEncodingToEncoding(encoding));
}
@end

用法:

NSString *urlText = @"http://google.com";
NSString *encodedUrlText = [urlText urlEncodeUsingEncoding:NSUTF8StringEncoding];
于 2013-02-04T14:45:30.063 回答