ios 替换 ios9 中的 stringByAddingPercentEscapesUsingEncoding?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32242712/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 07:25:13  来源:igfitidea点击:

Replacement for stringByAddingPercentEscapesUsingEncoding in ios9?

iosobjective-curlencodingdeprecated

提问by slavik

In iOS8 and prior I can use:

在 iOS8 及更早版本中,我可以使用:

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

in iOS9 stringByAddingPercentEscapesUsingEncodinghas been replaced with stringByAddingPercentEncodingWithAllowedCharacters:

在 iOS9 中stringByAddingPercentEscapesUsingEncoding已被替换为stringByAddingPercentEncodingWithAllowedCharacters

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

and my question is: where to find needed NSCharacterSet(NSUTF8StringEncoding) for proper replacement of stringByAddingPercentEscapesUsingEncoding?

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

回答by Antonio Favata

The deprecation message says (emphasis mine):

弃用消息说(强调我的):

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.

改用 stringByAddingPercentEncodingWithAllowedCharacters(_:) ,它始终使用推荐的 UTF-8 编码,并且为特定的 URL 组件或子组件编码,因为每个 URL 组件或子组件对哪些字符有效有不同的规则。

So you only need to supply an adequate NSCharacterSetas argument. Luckily, for URLs there's a very handy class method called URLHostAllowedCharacterSetthat you can use like this:

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

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

Update for Swift 3-- the method becomes the static property urlHostAllowed:

Swift 3 的更新——该方法成为静态属性urlHostAllowed

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

Be aware, though, that:

但请注意:

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

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

回答by ElonChan

For Objective-C:

对于Objective-C:

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

where to find set for NSUTF8StringEncoding?

在哪里可以找到 NSUTF8StringEncoding 的设置?

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

有六个 URL 组件和子组件的预定义字符集,允许百分比编码。这些字符集被传递给 -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

The deprecation message says (emphasis mine):

弃用消息说(强调我的):

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.

改用 stringByAddingPercentEncodingWithAllowedCharacters(_:) ,它始终使用推荐的 UTF-8 编码,并且为特定的 URL 组件或子组件编码,因为每个 URL 组件或子组件对哪些字符有效有不同的规则。

So you only need to supply an adequate NSCharacterSetas argument. Luckily, for URLs there's a very handy class method called URLHostAllowedCharacterSetthat you can use like this:

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

NSCharacterSet *set = [NSCharacterSet URLHostAllowedCharacterSet]; 

Be aware, though, that:

但请注意:

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

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

回答by Lal Krishna

URLHostAllowedCharacterSetis NOT WORKINGFOR ME. I use URLFragmentAllowedCharacterSetinstead.

URLHostAllowedCharacterSet不工作对我来说。我用URLFragmentAllowedCharacterSet代替。

OBJECTIVE -C

目标-C

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

SWIFT - 4

斯威夫特 - 4

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

The following are useful (inverted) character sets:

以下是有用的(倒置的)字符集:

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

回答by Bilal L

Objective-C

目标-C

this code work for me :

这段代码对我有用:

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

回答by Bobj-C

Swift 2.2:

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 { 
public static var urlHostAllowed: CharacterSet { get }

WebserviceCalls.getParamValueStringForURLFromDictionary(settingsDict as! Dictionary<String, AnyObject>).addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed)
== "/" }.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(
https://example.com?redirectme=xxxxx
) }.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; } }

回答by technerd

For Swift 3.0

对于 Swift 3.0

You can use urlHostAllowedcharacterSet.

您可以使用urlHostAllowed字符集。

/// Returns the character set for characters allowed in a host URL subcomponent.

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

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!

回答by kindaian

What is the meaning of "This method is intended to percent-encode an URL component or subcomponent string, NOT an entire URL string." ? – GeneCode Sep 1 '16 at 8:30

“此方法旨在对 URL 组件或子组件字符串进行百分比编码,而不是对整个 URL 字符串进行百分比编码”是什么意思。? – GeneCode 2016 年 9 月 1 日 8:30

It means that you are not supposed to encode the https://xpto.example.com/path/subpathof the url, but only what goes after the ?.

这意味着您不应该对https://xpto.example.com/path/subpathurl进行编码,而只能对?.

Supposed, because there are use-cases for doing it in cases like:

假设,因为在以下情况下有用例可以这样做:

##代码##

Where xxxxxis a fully encoded URL.

哪里xxxxx是完全编码的 URL。

回答by Ayman Ibrahim

Adding to the accepted answer. Taking into consideration this note

添加到已接受的答案。考虑到这个注释

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

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

the whole URL should not be encoded:

整个 URL 不应该被编码:

##代码##