简体   繁体   English

在ios9中替换stringByAddingPercentEscapesUsingEncoding?

[英]Replacement for stringByAddingPercentEscapesUsingEncoding in ios9?

In iOS8 and prior I can use: 在iOS8和之前我可以使用:

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

in iOS9 stringByAddingPercentEscapesUsingEncoding has 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 ? 我的问题是:在哪里找到所需的NSCharacterSetNSUTF8StringEncoding )来正确替换stringByAddingPercentEscapesUsingEncoding

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 NSCharacterSet as argument. 所以你只需要提供足够的NSCharacterSet作为参数。 Luckily, for URLs there's a very handy class method called URLHostAllowedCharacterSet that you can use like this: 幸运的是,对于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字符串进行编码。

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. 六个URL组件和子组件有预定义的字符集,允许百分比编码。 These character sets are passed to -stringByAddingPercentEncodingWithAllowedCharacters: . 这些字符集传递给-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 NSCharacterSet as argument. 所以你只需要提供足够的NSCharacterSet作为参数。 Luckily, for URLs there's a very handy class method called URLHostAllowedCharacterSet that you can use like this: 幸运的是,对于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字符串进行编码。

URLHostAllowedCharacterSet is NOT WORKING FOR ME. URLHostAllowedCharacterSet不是为我工作 I use URLFragmentAllowedCharacterSet instead. 我改用URLFragmentAllowedCharacterSet

OBJECTIVE -C 目标-C

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

SWIFT - 4 SWIFT - 4

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

The following are useful (inverted) character sets: 以下是有用的(反向)字符集:

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

Objective-C Objective-C的

this code work for me : 这段代码对我有用:

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

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;
}
}

For Swift 3.0 对于Swift 3.0

You can use urlHostAllowed characterSet. 您可以使用urlHostAllowed characterSet。

/// Returns the character set for characters allowed in a host URL subcomponent. ///返回主机URL子组件中允许的字符的字符集。

public static var urlHostAllowed: CharacterSet { get }

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

What is the meaning of "This method is intended to percent-encode an URL component or subcomponent string, NOT an entire URL string." “此方法旨在对URL组件或子组件字符串进行百分比编码,而不是整个URL字符串。” ? – GeneCode Sep 1 '16 at 8:30 - GeneCode 2016年9月1日8:30

It means that you are not supposed to encode the https://xpto.example.com/path/subpath of the url, but only what goes after the ? 这意味着你不应该对https://xpto.example.com/path/subpath进行编码,而只是对之后的内容进行编码? .

Supposed, because there are use-cases for doing it in cases like: 假设,因为在以下情况下有这样的用例:

https://example.com?redirectme=xxxxx

Where xxxxx is a fully encoded URL. 其中xxxxx是完全编码的URL。

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: 整个网址不应编码:

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!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM