替换 stringByAddingPercentEscapesUsingEncoding in ios9?

在 iOS8和之前的版本中,我可以使用:

NSString *str = ...; // some URL
NSString *result = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

在 iOS9stringByAddingPercentEscapesUsingEncoding已被 stringByAddingPercentEncodingWithAllowedCharacters取代:

NSString *str = ...; // some URL
NSCharacterSet *set = ???; // where to find set for NSUTF8StringEncoding?
NSString *result = [str stringByAddingPercentEncodingWithAllowedCharacters:set];

我的问题是: 在哪里可以找到所需的 NSCharacterSet(NSUTF8StringEncoding)来正确替换 stringByAddingPercentEscapesUsingEncoding

84698 次浏览

这条反对信息说(重点是我的) :

使用 stringByAddingPercentEncoding ingWithAllowedWords (_:)代替,它总是使用推荐的 UTF-8编码,并且为特定的 URL 组件或子组件进行编码,因为每个 URL 组件或子组件对于哪些字符是有效的有不同的规则。

所以您只需要提供一个足够的 NSCharacterSet作为参数。幸运的是,对于 URL,有一个非常方便的类方法 URLHostAllowedCharacterSet,您可以这样使用:

let encodedHost = unencodedHost.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())

Swift 3的更新——该方法变成了静态属性 urlHostAllowed:

let encodedHost = unencodedHost.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)

不过,请注意:

此方法用于对 URL 组件或子组件字符串进行百分比编码,而不是对整个 URL 字符串进行百分比编码。

目标 C:

NSString *str = ...; // some URL
NSCharacterSet *set = [NSCharacterSet URLHostAllowedCharacterSet];
NSString *result = [str stringByAddingPercentEncodingWithAllowedCharacters:set];

在哪里可以找到 NSUTF8StringEncoding 的集合?

There are predefined character sets for the six URL components and subcomponents which allow percent encoding. These character sets are passed to -stringByAddingPercentEncodingWithAllowedCharacters: .

 // Predefined character sets for the six URL components and subcomponents which allow percent encoding. These character sets are passed to -stringByAddingPercentEncodingWithAllowedCharacters:.
@interface NSCharacterSet (NSURLUtilities)
+ (NSCharacterSet *)URLUserAllowedCharacterSet;
+ (NSCharacterSet *)URLPasswordAllowedCharacterSet;
+ (NSCharacterSet *)URLHostAllowedCharacterSet;
+ (NSCharacterSet *)URLPathAllowedCharacterSet;
+ (NSCharacterSet *)URLQueryAllowedCharacterSet;
+ (NSCharacterSet *)URLFragmentAllowedCharacterSet;
@end

这条反对信息说(重点是我的) :

Use stringByAddingPercentEncodingWithAllowedCharacters(_:) instead, 它总是使用推荐的 UTF-8编码, 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,您可以这样使用:

NSCharacterSet *set = [NSCharacterSet URLHostAllowedCharacterSet];

不过,请注意:

此方法用于对 URL 组件或子组件字符串进行百分比编码,而不是对整个 URL 字符串进行百分比编码。

Swift 2.2:

extension String {
func encodeUTF8() -> String? {
//If I can create an NSURL out of the string nothing is wrong with it
if let _ = NSURL(string: self) {


return self
}


//Get the last component from the string this will return subSequence
let optionalLastComponent = self.characters.split { $0 == "/" }.last




if let lastComponent = optionalLastComponent {


//Get the string from the sub sequence by mapping the characters to [String] then reduce the array to String
let lastComponentAsString = lastComponent.map { String($0) }.reduce("", combine: +)




//Get the range of the last component
if let rangeOfLastComponent = self.rangeOfString(lastComponentAsString) {
//Get the string without its last component
let stringWithoutLastComponent = self.substringToIndex(rangeOfLastComponent.startIndex)




//Encode the last component
if let lastComponentEncoded = lastComponentAsString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.alphanumericCharacterSet()) {




//Finally append the original string (without its last component) to the encoded part (encoded last component)
let encodedString = stringWithoutLastComponent + lastComponentEncoded


//Return the string (original string/encoded string)
return encodedString
}
}
}


return nil;
}
}

为了 Swift 3.0

您可以使用 urlHostAllowed字符集。

///返回宿主 URL 子组件中允许的字符的字符集。

public static var urlHostAllowed: CharacterSet { get }


WebserviceCalls.getParamValueStringForURLFromDictionary(settingsDict as! Dictionary<String, AnyObject>).addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed)

目标 C

这个代码对我有用:

urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];

“此方法旨在对 URL 组件或子组件字符串进行百分比编码,而不是对整个 URL 字符串进行百分比编码。”?基因编码9月1日16日8:30

这意味着你不应该编码的 https://xpto.example.com/path/subpath的网址,但只有什么去后面的 ?

假设,因为有这样的用例:

https://example.com?redirectme=xxxxx

其中 xxxxx是完全编码的 URL。

对我来说,URLHostAllowedCharacterSet没用。我用 URLFragmentAllowedCharacterSet代替。

OBJECTIVE -C

NSCharacterSet *set = [NSCharacterSet URLFragmentAllowedCharacterSet];
NSString * encodedString = [@"url string" stringByAddingPercentEncodingWithAllowedCharacters:set];

SWIFT-4

"url string".addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)

下面是有用的(反向的)字符集:

URLFragmentAllowedCharacterSet  "#%<>[\]^`{|}
URLHostAllowedCharacterSet      "#%/<>?@\^`{|}
URLPasswordAllowedCharacterSet  "#%/:<>?@[\]^`{|}
URLPathAllowedCharacterSet      "#%;<>?[\]^`{|}
URLQueryAllowedCharacterSet     "#%<>[\]^`{|}
URLUserAllowedCharacterSet      "#%/:<>?@[\]^`

增加了公认的答案。 考虑到这张纸条

This method is intended to percent-encode an URL component or subcomponent string, NOT an entire URL string.

整个网址不应编码:

let param = "=color:green|\(latitude),\(longitude)&\("zoom=13&size=\(width)x\(height)")&sensor=true&key=\(staticMapKey)".addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
let url = "https://maps.google.com/maps/api/staticmap?markers" + param!