想要對部分URL字符串進行百分號編碼,請使用NSString的stringByAddingPercentEncodingWithAllowedCharacters:方法暂衡,給URL組件或子組件傳遞合適的字符集:
- User: URLUserAllowedCharacterSet
- Password: URLPasswordAllowedCharacterSet
- Host: URLHostAllowedCharacterSet
- Path: URLPathAllowedCharacterSet
- Fragment(片段): URLFragmentAllowedCharacterSet
- Query(查詢): URLQueryAllowedCharacterSet
重要:不要使用stringByAddingPercentEncodingWithAllowedCharacters:來編碼整個URL字符串芽隆,因為每個URL組件或子組件對于有效字符都有不同的規(guī)則浊服。
例如,想要對包含在URL片段中的UTF-8字符串進行百分號編碼胚吁,請執(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"
如果你想對URL組件進行百分號編碼牙躺,使用NSURLComponents把URL分拆成它的組成部分,并訪問相關的屬性腕扶。
例如孽拷,想要得到URL片段百分號編碼的UTF-8字符串值,請執(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"