URL coding Problems in iOS
Roche (http://www.cnblogs.com/kesalin/) This article follows the authoring common agreement "signed-non-commercial-Consistent"
NSString's stringbyaddingpercentescapesusingencoding can encode URL parameters, but there is a slight problem that does not encode all the characters that need to be encoded. We can go through the cfstringref.
Cfurlcreatestringbyaddingpercentescapes function to encapsulate this function. The code is as follows:
-(NSString *) encodetopercentescapestring: (NSString *) input
{
Encode all of the reserved characters, per RFC 3986
(NSString *outputstr = (NSString *)
Cfurlcreatestringbyaddingpercentescapes (Kcfallocatordefault,
(cfstringref) input,
Null
(cfstringref) @ "!* ' ();: @&=+$,/?%#[]",
KCFSTRINGENCODINGUTF8);
return outputstr;
}
-(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);
The results are as follows:
>> original: http://search.google.com?keywords= ($# it ' s {a*123}) 00!* ' ();: @&=+$,/?%#[]
>> encoded:http%3a%2f%2fsearch.google.com%3fkeywords%3d%28%24%23%20it%27s%20%7ba%2a123%7d%2900%21%2a%27% 28%29%3B%3A%40%26%3D%2B%24%2C%2F%3F%25%23%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!* ' ();: @&=+$,/?%#[] sharing