By using the NSString default URL encoding, characters such as Kanji are escaped, but the characters such as =+ are not escaped
So to manually implement the escape of these characters
-(NSString *) encodetopercentescapestring: (NSString *) Input {//Encode all the reserved characters, per RFC 3986//(<Http://www.ietf.org/rfc/rfc3986.txt>)NSString *outputstr = (NSString *) Cfurlcreatestringbyaddingpercentescapes (Kcfallocatordefault, (CFS TRINGREF) input, NULL, (Cfstringr EF)@"!* ' ();: @&=+$,/?%#[]", kCFStringEncodingUTF8); returnOutputstr; } -(NSString *) decodefrompercentescapestring: (NSString *) input {nsmutablestring*outputstr =[nsmutablestring Stringwithstring:input]; [Outputstr replaceoccurrencesofstring:@"+"withstring:@" "Options:nsliteralsearch Range:nsmakerange (0, [outputstr length])]; return[Outputstr stringbyreplacingpercentescapesusingencoding:nsutf8stringencoding]; }
Test code
NSString * Testurl =@"http://search.google.com?keywords= ($# it ' s {a*123}) 00!* ' ();: @&=+$,/?%#[]"; NSLog (@"Original:%@", Testurl); NSString* Encodestr =[self encodetopercentescapestring:testurl]; NSLog (@"encoded:%@", ENCODESTR); NSString* ENCODESTR2 =[Testurl stringbyaddingpercentescapesusingencoding:nsutf8stringencoding]; NSLog (@"encoded2:%@", ENCODESTR2); NSString* Decodestr =[self decodefrompercentescapestring:encodestr]; NSLog (@"Decoded:%@", DECODESTR);
Results
>> original:http://search.google.com?keywords= ($# it ' s {a*123}) 00!* ' ();: @&=+$,/?%#[]>> encoded:http%3a%2f%2fsearch.google.com%3fkeywords%3d% -% -% at%20it%27s% -%7ba%2a123%7d%2900% +%2a% -% -% in%3b%3a% +% -%3d%2b% -%2c%2f%3f% -% at%5b%5D>> encoded2:http://search.google.com?keywords= ($%23%20it ' s%20%7ba*123%7d) 00!* ' ();: @&=+$,/?%25%23%5b%5d>> decoded:http://search.google.com?keywords= ($# it ' s {a*123}) 00!* ' ();: @&=+$,/?%#[]
Transferred from: http://blog.csdn.net/kesalin/article/details/6678939
URL encoding under iOS