把下面提到的component和subcomponent理解成不同的部件,对于URL: 协议(http)、主机(www.baidu.com)、端口()、文件路径等等都叫一个部件。

对URL字符串的一部分进行百分号编码(比如中文在传输过程会被编码出现各种百分号),使用NSString的方法stringByAddingPercentEncodingWithAllowedCharacters:,传给URL的component或者subcomponent恰当的字符集:

⚠️⚠️⚠️ 特别注意

千万不要用stringByAddingPercentEncodingWithAllowedCharacters:方法去encode整个URL字符串,因为URL的component和subcomponent处理哪些字符是有效的有不同的规则。

例如下面对一个包含了URL分段的UTF-8字符串进行百分号编码,我们可以这么做:

/// Objective-C
NSString *originalString = @"color-#708090";
NSCharacterSet *allowedCharacters = [NSCharacterSet URLFragmentAllowedCharacterSet];
NSString *percentEncodedString = [originalString stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters];
NSLog(@"%@", percentEncodedString"); // prints "color-%23708090"
/// Swift
let originalString = "color-#708090"
let allowedCharacters = NSCharacterSet.urlFragmentAllowed
let encodedString = originalString.addingPercentEncoding(withAllowedCharacters: allowedCharacters)
print(encodedString!) // prints "color-%23708090"

如果想要decode(解码)一个被百分号编码的URL component的话,使用NSURLComponents进行拆分成各个组成部分,并去访问相应的属性。

例如一个百分号编码的URL分段,获取它的UTF-8字符串,我们可以像下面这么做:

/// Objective-C
NSURL *URL = [NSURL URLWithString:@"https://example.com/#color-%23708090"];
NSURLComponents *components = [NSURLComponents componentsWithURL:URL resolvingAgainstBaseURL:NO];
NSString *fragment = components.fragment;
NSLog(@"%@", fragment); // prints "color-#708090"
/// Swift
let url = URL(string: "https://example.com/#color-%23708090")!
let components = URLComponents(url: url, resolvingAgainstBaseURL: true)!
let fragment = components.fragment!
print(fragment) // prints "color-#708090"

results matching ""

    No results matching ""