替换 ios9 中的 stringByAddingPercentEscapesUsingEncoding?

Replacement for stringByAddingPercentEscapesUsingEncoding in ios9?

在iOS8之前我可以使用:

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

在 iOS9 stringByAddingPercentEscapesUsingEncoding 已替换为 stringByAddingPercentEncodingWithAllowedCharacters:

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

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

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

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,有一个非常方便的 class 方法,称为 URLHostAllowedCharacterSet,您可以像这样使用它:

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

更新 Swift 3 -- 方法变为静态 属性 urlHostAllowed:

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

不过请注意:

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

对于Objective-C:

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

在哪里可以找到 NSUTF8StringEncoding 集?

六个 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

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

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 作为参数。幸运的是,对于 URLs 有一个非常方便的 class 方法叫做 URLHostAllowedCharacterSet,你可以像这样使用它:

NSCharacterSet *set = [NSCharacterSet URLHostAllowedCharacterSet]; 

不过请注意:

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

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 { [=10=] == "/" }.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([=10=]) }.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 字符集。

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

public static var urlHostAllowed: CharacterSet { get }

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

Objective-C

这段代码对我有用:

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

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 的 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.

整个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!