来自 NSURLComponents 的 URL 查询项为 nill



我正在创建一个NSURLURL将包含一些转义字符(日语(

NSString* currentlocationbarString = @"mbos.help.jp/search?q=専門&pg=1"
NSString *escapedString = [currentlocationbarString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
NSURL* url = [NSURL URLWithString:escapedString];
/

/url is mbos.help.jp%2Fsearch%3Fq=%E5%B0%82%E9%96%80&pg=1

当我创建NSURLComponents并尝试获取查询项时,它给我零。

NSURLComponents *urlComponents = [NSURLComponents componentsWithURL:url
resolvingAgainstBaseURL:YES];
NSArray *queryItems = urlComponents.queryItems;

查询项的问题

如果有人有解决方案来获取查询项目,请提供帮助。提前致谢

问题不在于 Unicode 字符,每当您添加编码时,我都使用以下字符集URLHostAllowedCharacterSet这意味着您的NSURLComponents只为您的主机提供编码,以获得正确的queryItems像这样使用URLQueryAllowedCharacterSet

NSString* currentlocationbarString = @"mbos.help.jp/search?q=専門&pg=1"
NSString *escapedString = [currentlocationbarString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSURL* url = [NSURL URLWithString:escapedString];

所以现在你可以得到queryItems。

NSURLComponents *urlComponents = [NSURLComponents componentsWithURL:url
resolvingAgainstBaseURL:YES];
NSArray *queryItems = urlComponents.queryItems;

您在搜索字符串中使用的字符 専門中至少有一个是无效的 Unicode,其形式为未配对的 UTF-16 代理项字符,因此不能由stringByAddingPercentEncodingWithAllowedCharacters:编码,因此返回nil
您可以在这篇文章中找到一个例子。
显然,如果编码可以,您必须检查日语字符。
我必须说,我也没想到!

最新更新