我正在尝试构建一个 url 并确保对路径中的所有特殊字符进行编码,我目前未能这样做,可能是由于对 path
属性的误解NSURLComponents
有效。
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]];
//返回带“!”的 url,未编码
[items addObject:components.URL];
我在 components.path
中做错了什么吗?
提前感谢大家的帮助。
最佳答案
由于 URLPathAllowedCharacterSet
包含“!”,您需要通过创建 URLPathAllowedCharacterSet
的可变副本并删除“!”来创建新的字符集:
NSMutableCharacterSet *characterSet = [[NSCharacterSet URLPathAllowedCharacterSet] mutableCopy];
[characterSet removeCharactersInString:@"!"];
关于ios - URLPathAllowedCharacterSet 不编码感叹号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43401456/