在ios9中替换stringByAddingPercentEscapesUsingEncoding?
在iOS8之前,我可以使用:
In iOS8 and prior I can use:
NSString *str = ...; // some URL
NSString *result = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
stringByAddingPercentEscapesUsingEncoding 已被替换为 stringByAddingPercentEncodingWithAllowedCharacters
:
in iOS9 stringByAddingPercentEscapesUsingEncoding
has been replaced with stringByAddingPercentEncodingWithAllowedCharacters
:
NSString *str = ...; // some URL
NSCharacterSet *set = ???; // where to find set for NSUTF8StringEncoding?
NSString *result = [str stringByAddingPercentEncodingWithAllowedCharacters:set];
我的问题是:在哪里找到需要的 NSCharacterSet
( NSUTF8StringEncoding
)正确替换 stringByAddingPercentEscapesUsingEncoding
?
and my question is: where to find needed NSCharacterSet
(NSUTF8StringEncoding
) for proper replacement of stringByAddingPercentEscapesUsingEncoding
?
弃用消息说(强调我的):
The deprecation message says (emphasis mine):
使用stringByAddingPercentEncodingWithAllowedCharacters ,始终使用推荐的UTF-8编码,并且编码特定的URL组件或子组件,因为每个URL组件或子组件对于哪些字符有效,具有不同的规则。
Use stringByAddingPercentEncodingWithAllowedCharacters(_:) instead, which always uses the recommended UTF-8 encoding, and which encodes for a specific URL component or subcomponent since each URL component or subcomponent has different rules for what characters are valid.
所以你只需要提供一个足够的 NSCharacterSet
作为参数。幸运的是,对于URL,有一个非常方便的类方法叫做 URLHostAllowedCharacterSet
,你可以这样使用:
So you only need to supply an adequate NSCharacterSet
as argument. Luckily, for URLs there's a very handy class method called URLHostAllowedCharacterSet
that you can use like this:
let encodedHost = unencodedHost.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
em> Swift 3 - 该方法成为静态属性 urlHostAllowed
:
Update for Swift 3 -- the method becomes the static property urlHostAllowed
:
let encodedHost = unencodedHost.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
,那就是:
此方法用于对URL组件或子组件字符串进行百分比编码,而不是整个URL字符串。
This method is intended to percent-encode an URL component or subcomponent string, NOT an entire URL string.