这是一个有效的URL,如果是这样,为什么NSURL无法识别其查询? [英] Is this a valid URL, and if so why does NSURL not recognize its query?
问题描述
myscheme:?id=test
如果我通过了到 [NSURL URLWithString:]
并打印其 query
属性,我得到 nil
,但如果我在冒号(或两个或三个)后放一个斜杠,就可以了。
If I pass this to [NSURL URLWithString:]
and print its query
property, I get nil
, but if I put a slash right after the colon (or two or three) it works fine.
这实际上是无效的URL还是它 NSURL
中的错误?
Is this actually an invalid URL or is it a bug in NSURL
?
根据一些研究,它似乎是有效的URL。来自 http://url.spec.whatwg.org/ :
According to some research, it appears to be a valid URL. From http://url.spec.whatwg.org/:
绝对URL必须是一个方案,后跟:,然后是方案
数据,还可以是?
An absolute URL must be a scheme, followed by ":", followed by scheme data, optionally followed by "?" and a query.
和(强调)
方案数据的语法取决于方案,通常在
旁边定义。对于相对方案,方案数据必须是
方案相对URL。 对于其他方案,规范或标准
必须在零个或更多 URL
个单位的约束内定义方案数据。
The syntax of scheme data depends on the scheme and is typically defined alongside it. For a relative scheme, scheme data must be a scheme-relative URL. For other schemes, specifications or standards must define scheme data within the constraints of zero or more URL units.
推荐答案
myscheme:?id = test
是有效的网址,并且 NSURL
通过从 + URLWithString返回非<
nil
来识别它, code>。
myscheme:?id=test
is a valid URL, and NSURL
recognises it as such, by returning non-nil
from +URLWithString:
.
但是,根据RFC 1808,它的格式不符合 NSURL
识别?
字符表示查询字符串,因此 -query
返回 nil
。
However, by RFC 1808, it doesn't conform in a manner such that NSURL
recognises the ?
character as indicating a query string, so -query
returns nil
.
这里的好消息是 NSURLComponents
的解析器与将识别为?
表示对您的示例的查询:
The good news here is that NSURLComponents
has a slightly different parser which will recognise the ?
as indicating a query for your example:
NSURLComponents *components = [NSURLComponents componentsWithString:@"myscheme:?id=test"];
return components.query; // returns @"id=test"
如果您仍然需要以此为目标的iOS 6或更早版本代码,建议您使用 KSURLComponents
类而是采用相同的解析方法。
If you still need to target iOS 6 or earlier with this code, I suggest using my KSURLComponents
class instead, which takes the same parsing approach.
这篇关于这是一个有效的URL,如果是这样,为什么NSURL无法识别其查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!