What are the characters that stringByAddingPercentEscapesUsingEncoding escapes?

半城伤御伤魂 提交于 2020-01-03 09:04:11

问题


I've had to switch from stringByAddingPercentEscapesUsingEncoding to CFURLCreateStringByAddingPercentEscapes because it doesn't escape question marks (?). I'm curious what exactly it does escape, and the rationale behind the partial escaping vs RFC 3986.


回答1:


Some good categories have been created for doing just what you need: http://iosdevelopertips.com/networking/a-better-url-encoding-method.html http://www.cocoanetics.com/2009/08/url-encoding/

The rationale for leaving certain characters out is beyond me... except to say that the definition of the function is: Returns a representation of the receiver using a given encoding to determine the percent escapes necessary to convert the receiver into a legal URL string.

To be completely correct, + and & are legal characters within a URL, whereas a space is not. Hence the method will correctly escape a space, but leaves + and & intact.

Reading RFC2396 http://www.ietf.org/rfc/rfc2396.txt - there is a set of reserved and unreserved characters defined. My guess is that none of these characters are escaped by stringByAddingPercentEscapesUsingEncoding.




回答2:


Be careful not to leak memory on conversions when using CFStringRef. Here's what I came up with to work with Latin characters, and others. I use this to escape my parameters, not the entire URL. Depending on your use case, you may need to add or remove characters from "escapeChars"

CFStringRef escapeChars = (CFStringRef)@"%;/?¿:@&=$+,[]#!'()*<>¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ \"\n";

NSString *encodedString = (__bridge_transfer NSString *) CFURLCreateStringByAddingPercentEscapes(NULL, (__bridge_retained CFStringRef) url, NULL, escapeChars, kCFStringEncodingUTF8);

I hope this helps.



来源:https://stackoverflow.com/questions/8693923/what-are-the-characters-that-stringbyaddingpercentescapesusingencoding-escapes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!