2017-04-13 175 views
0

我正在嘗試構建一個url並確保路徑中的所有特殊字符都已編碼,我目前未能這樣做,可能是由於誤解了path屬性NSURLComponents作品。URLPathAllowedCharacterSet不編碼感嘆號

NSURLComponents *components = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:NO]; 

NSURLQueryItem *queryItem = [NSURLQueryItem queryItemWithName: @"queryName" value: @"queryValue"]; 
components.queryItems = @[queryItem]; 

//我認爲stringByAddingPercentEncodingWithAllowedCharacters將編碼字符一樣 「!」到 「%21」

components.path = [components.path stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLPathAllowedCharacterSet]]; 

//返回以 「!」 一個網址,未編碼的

[items addObject:components.URL]; 

我做得根本錯誤的components.path

感謝大家提前給予的幫助。

回答

1

由於URLPathAllowedCharacterSet包含「!」,你需要創建一個通過創建URLPathAllowedCharacterSet的可變副本並刪除「!」來創建新字符集:

NSMutableCharacterSet *characterSet = [[NSCharacterSet URLPathAllowedCharacterSet] mutableCopy]; 
[characterSet removeCharactersInString:@"!"]; 
1

URLPathAllowedCharacterSet不包括「!」,因而它不會被編碼

可以使用枚舉這套這個程序

NSCharacterSet *set = [NSCharacterSet URLPathAllowedCharacterSet]; 

    for (int plane = 0; plane <= 16; plane++) { 
     if ([set hasMemberInPlane:plane]) { 
      UTF32Char c; 
      for (c = plane << 16; c < (plane+1) << 16; c++) { 
       if ([set longCharacterIsMember:c]) { 
        UTF32Char c1 = OSSwapHostToLittleInt32(c); // To make it byte-order safe 
        NSString *s = [[NSString alloc] initWithBytes:&c1 length:4 encoding:NSUTF32LittleEndianStringEncoding]; 
        NSLog(@"%@", s); 
       } 
      } 
     } 
    }