我正在尝试构建一个url,并确保路径中的所有特殊字符都已编码,但由于无法正确理解pathNSURLComponents属性的工作方式,我目前未能这样做。

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中做根本上错误的事情吗?

预先感谢大家的帮助。

最佳答案

由于URLPathAllowedCharacterSet包含“!”,因此您需要通过创建URLPathAllowedCharacterSet的可变副本并删除“!”来创建新的字符集:

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

关于ios - URLPathAllowedCharacterSet不编码感叹号,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43401456/

10-15 08:08