替换 ios9 中的 stringByAddingPercentEscapesUsingEncoding?
在 iOS8 及更早版本中我可以使用:
In iOS8 and prior I can use:
NSString *str = ...; // some URL
NSString *result = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
在 iOS9 中 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())
更新 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.