想要對(duì)部分URL字符串進(jìn)行百分號(hào)編碼,請(qǐng)使用NSString的stringByAddingPercentEncodingWithAllowedCharacters:方法,給URL組件或子組件傳遞合適的字符集:
- User: URLUserAllowedCharacterSet
- Password: URLPasswordAllowedCharacterSet
- Host: URLHostAllowedCharacterSet
- Path: URLPathAllowedCharacterSet
- Fragment(片段): URLFragmentAllowedCharacterSet
- Query(查詢(xún)): URLQueryAllowedCharacterSet
重要:不要使用stringByAddingPercentEncodingWithAllowedCharacters:來(lái)編碼整個(gè)URL字符串,因?yàn)槊總€(gè)URL組件或子組件對(duì)于有效字符都有不同的規(guī)則。
例如,想要對(duì)包含在URL片段中的UTF-8字符串進(jìn)行百分號(hào)編碼,請(qǐng)執(zhí)行如下操作:
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"
如果你想對(duì)URL組件進(jìn)行百分號(hào)編碼,使用NSURLComponents把URL分拆成它的組成部分,并訪問(wèn)相關(guān)的屬性。
例如,想要得到URL片段百分號(hào)編碼的UTF-8字符串值,請(qǐng)執(zhí)行以下操作:
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"