ios - NSURLComponents elementsWithString - 规则

标签 ios objective-c nsurl

我正在编写单元测试来测试 URL 生成器类。

我正在使用 NSURLComponents elementsWithString] 生成最终的 URL 对象。

是否存在关于 componentsWithString 如何转义正斜杠 (/) 的规则?

情况1:

NSURLComponents *urlComponents = [NSURLComponents componentsWithString: @"/foo"];
urlComponents.scheme = @"http";
urlComponents.host = [NSString stringWithFormat:@"www.bar.com"];
// [urlComponents URL] = http://www.bar.com/foo - Seems okay

情况2:

NSURLComponents *urlComponents = [NSURLComponents componentsWithString: @"////foo"];
urlComponents.scheme = @"http";
urlComponents.host = [NSString stringWithFormat:@"www.bar.com"];
// [urlComponents URL] = http://www.bar.com//foo

情况3:

NSURLComponents *urlComponents = [NSURLComponents componentsWithString: @"//////foo"];
urlComponents.scheme = @"http";
urlComponents.host = [NSString stringWithFormat:@"www.bar.com"];
// [urlComponents URL] = http://www.bar.com////foo

为什么案例 2 和案例 3 分别将斜线数量减少到 2 和 4?

最佳答案

您的情况 2 和 3 不符合 NSURLComponents 文档中指定的 RFC 3986 路径格式:https://developer.apple.com/documentation/foundation/nsurlcomponents?language=objc

The NSURLComponents class is a class that is designed to parse URLs based on RFC 3986 and to construct URLs from their constituent parts.

从路径部分:https://www.rfc-editor.org/rfc/rfc3986#section-3.3 RFC 3986 规范提到路径不能以 // 开头,除非有权限组件:

If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//").

如果您调整案例 2 和 3,使其之间至少有一个字符,如下所示:

NSURLComponents *urlComponents = [NSURLComponents componentsWithString: @"/a/////foo"];

我相信它应该输出正确数量的斜杠。

关于ios - NSURLComponents elementsWithString - 规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54560732/

相关文章:

objective-c - 试图关闭 subview 和 UIView

ios - 插入 block 回调到 NSMutableDictionary

iphone - 带有 NSURLErrorDomain 错误 -999 的 weblock 错误

iphone - 如何实现像通知中心的股票行情自动 ScrollView ?

ios - 从UIControl显示UIPopoverPresentationController吗?

ios - ECSlidingViewController 移除 PanGesture

ios - NSURLRequestReloadIgnoringLocalAndRemoteCacheData 在 iOS 7 中工作吗?

iphone - nsurlconnection 服务器需要特殊设置吗?

ios - "Internet connection is offline"在没有互联网接入的情况下连接到 AP 时 - WiFi 关闭/打开修复

ios - 使用 URLSession 将视频上传到 Vimeo