2017-04-13 179 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); 
       } 
      } 
     } 
    }