方法1:
NSString* encodedString = [urlStringstringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
方法2:
NSString * encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)urlString,NULL,NULL,kCFStringEncodingUTF8);
如果在所有的类里都要用到这个方法,可以写成category,然后在头文件import "NSString+URL.h" 即可调用.
NSString+URL.h 文件
@interface NSString (URL) - (NSString *)URLEncodedString; @end
NSString+URL.m 文件
#import "NSString+URL.h" @implementation NSString (URL) - (NSString *)URLEncodedString { NSString *encodedString = (NSString *) CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)self, (CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]", NULL, kCFStringEncodingUTF8); return encodedString; } @end
调用方法:
NSString *encodedString = [urlString URLEncodedString];
//encodedString do something