我最近在比较两个NSString和一个NSURLRequest (这是一个网址)时遇到了一个问题,情况是我从某个地方得到了一个NSString,我可能知道也可能不知道它指向的网址,我有一个URL,比如"http://m.google.com",现在我需要检查该NSURLRequest中的URL是否与我拥有的URL字符串相同:
[[request.URL.absoluteString lowercaseString] isEqualToString: [self.myAddress lowercaseString]];
这将返回NO,因为absoluteString
给了我"http://m.google.com/“,而我的字符串是"http://m.google.com”,末尾没有斜杠,即使我使用
[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://m.google.com"]]
它仍然为我提供了absoluteString
的"http://m.google.com/“,我想知道有什么可靠的方法来比较NSURL或一个NSURL和一个NSString吗?
isEqual
方法比较两个NSURL,希望NSURL的isEqual
实现可以根据步骤2找出它?非常感谢!
发布于 2012-09-08 23:39:33
如果您只关心尾部斜杠的多义性,您可以通过知道NSURL路径修剪尾部斜杠来快速省略这个问题。
但我喜欢在NSURL上使用类别方法的想法,它实现了一些基于标准的等价(在这种情况下,“等价”可能是一个比相等更好的术语)。
@RobNapier指的是一个相关的问题,它有一个好的答案,指向RFC2616。url语法的另一个相关标准是RFC1808。
困难的部分是决定我们所说的等价性是什么意思,例如,不同的查询或片段(锚链)怎么办?下面的代码对于这些歧义中的大多数都是错误的。
// in NSURL+uriEquivalence.m
- (BOOL)isEquivalent:(NSURL *)aURL {
if ([self isEqual:aURL]) return YES;
if ([[self scheme] caseInsensitiveCompare:[aURL scheme]] != NSOrderedSame) return NO;
if ([[self host] caseInsensitiveCompare:[aURL host]] != NSOrderedSame) return NO;
// NSURL path is smart about trimming trailing slashes
// note case-sensitivty here
if ([[self path] compare:[aURL path]] != NSOrderedSame) return NO;
// at this point, we've established that the urls are equivalent according to the rfc
// insofar as scheme, host, and paths match
// according to rfc2616, port's can weakly match if one is missing and the
// other is default for the scheme, but for now, let's insist on an explicit match
if ([self port] || [aURL port]) {
if (![[self port] isEqual:[aURL port]]) return NO;
if (![[self query] isEqual:[aURL query]]) return NO;
}
// for things like user/pw, fragment, etc., seems sensible to be
// permissive about these.
return YES;
}
发布于 2017-06-09 17:40:05
我知道这是有答案的。但我不认为,这是明确的。
我想推荐以下几点。
if ([[url1 absoluteString] isEqualToString:[url2 absoluteString]])
{
//Add your implementation here
}
发布于 2019-01-15 08:34:39
我最近遇到过在比较两个URL(如https://www.google.com/
和https://www.google.com
)时[NSURL isEqual]
方法返回false的情况,我发现将带有空字符串作为参数的URLByAppendingPathComponent
应用于两个URL将返回正确的结果。
所以就像这样:
[[urlOne URLByAppendingPathComponent:@""] isEqual:[urlTwo URLByAppendingPathComponent:@""]]
如果缺少则添加尾部斜杠,如果已包含则保持不变,因此比较将按预期进行。
在我看来,我似乎依赖于一种奇怪的行为来工作-绕过另一种奇怪的行为,但这就是我要做的,除非我能被说服;-)
https://stackoverflow.com/questions/12310258
复制相似问题