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

标签 iphone ios nsurl

我发现 [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/

相关文章:

ios - 无法使用类型为 'findObjectsInBackgroundWithBlock' 的参数列表调用 '(([AnyObject]!, NSError!) -> Void)'

ios - Swift UI 测试 TextField 中的访问字符串

ios - 在 Swift 上从 URL 加载/下载图像

ios - 使用 NSURLConnection 连续发送 100 多个请求并在发送下一个请求之前等待每个响应

iphone - iTunes 中是否有任何更改以上传新的二进制文件。?

ios - InApp Purchase 产品列表不会在 iPhone 应用程序中加载

iphone - 如何识别来自iphone的用户点击 "home screen"

ios - Xcode:如何在用户选择语言时更改应用程序的语言?

ios - 无论如何,异步 NSURLconnection 是否有助于实时更新或向 iOS 应用程序中的服务器发送持续请求?

iphone - 逐像素检查 UIImage