草庐IT

iphone - 为什么 [NSURL URLWithString :] escapes some characters in url string and doesn't for other characters?

coder 2024-01-11 原文

我发现 [NSURL URLWithString:] 方法会自动转义传递给它的 url 字符串中的某些字符。例如它逃脱了括号。但 url 字符串包含其他非法 url 字符,如 < 和=""> 导致方法返回 nil

[[NSURL URLWithString:@"http://foo.bar/?key[]=value[]"] absoluteString]

返回与

相同的结果
[@"http://foo.bar/?key[]=value[]" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]

同时,

[NSURL URLWithString:@"http://foo.bar/?key[]=value[]<>"] returns nil, not a url with an escaped string.

在启动 NSURL 实例的过程中到底发生了什么?为什么它(也许)只转义括号?

最佳答案

NSUrl URLWithString:不会转义文档中所述的字符串:

This method expects URLString to contain any necessary percent escape codes, which are ‘:’, ‘/’, ‘%’, ‘#’, ‘;’, and ‘@’. Note that ‘%’ escapes are translated via UTF-8

但是,您应该能够使用 stringByAddingPercentEscapesUsingEncoding: 执行以下操作:

NSString *myString = @"http://foo.bar/?key[]=value[]<>";
NSURL *myUrl = [NSURL URLWithString:[myString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

关于iphone - 为什么 [NSURL URLWithString :] escapes some characters in url string and doesn't for other characters?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7996338/

有关iphone - 为什么 [NSURL URLWithString :] escapes some characters in url string and doesn't for other characters?的更多相关文章

随机推荐