想要对部分URL字符串进行百分号编码,请使用NSString的stringByAddingPercentEncodingWithAllowedCharacters:方法,给URL组件或子组件传递合适的字符集:
- User: URLUserAllowedCharacterSet
- Password: URLPasswordAllowedCharacterSet
- Host: URLHostAllowedCharacterSet
- Path: URLPathAllowedCharacterSet
- Fragment(片段): URLFragmentAllowedCharacterSet
- Query(查询): URLQueryAllowedCharacterSet
重要:不要使用stringByAddingPercentEncodingWithAllowedCharacters:来编码整个URL字符串,因为每个URL组件或子组件对于有效字符都有不同的规则。
例如,想要对包含在URL片段中的UTF-8字符串进行百分号编码,请执行如下操作:
NSString *originalString = @"color-#708090";
NSCharacterSet *allowedCharacters = [NSCharacterSet URLFragmentAllowedCharacterSet];
NSString *percentEncodedString = [originalString stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters];
NSLog(@"%@", percentEncodedString"); // prints "color-%23708090"
let originalString = "color-#708090"
let allowedCharacters = NSCharacterSet.urlFragmentAllowed
let encodedString = originalString.addingPercentEncoding(withAllowedCharacters: allowedCharacters)
print(encodedString!) // prints "color-%23708090"
如果你想对URL组件进行百分号编码,使用NSURLComponents把URL分拆成它的组成部分,并访问相关的属性。
例如,想要得到URL片段百分号编码的UTF-8字符串值,请执行以下操作:
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"
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"