URL encoding under iOS

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.