Reliable way to compare two NSURL or one NSURL and an NSString?
I know this is answered. But i don't think , its clear.
I would like to recommend the following.
if ([[url1 absoluteString] isEqualToString:[url2 absoluteString]])
{
//Add your implementation here
}
Having recently encountered the situation where the [NSURL isEqual]
method returns false when comparing two URLs like https://www.google.com/
and https://www.google.com
I have found that applying the URLByAppendingPathComponent
with an empty-string as the parameter to both URLs will return the correct result.
So something like:
[[urlOne URLByAppendingPathComponent:@""] isEqual:[urlTwo URLByAppendingPathComponent:@""]]
will add the trailing slash if missing and leave it alone if it is already included and so the comparison will work as expected.
Seems to me like I am relying on one strange behavior to work-around another strange behavior but this is what I am going with unless I can be convinced otherwise ;-).
If you care only about the trailing slash ambiguity, you can dispense with this question quickly by knowing that NSURL path trims the trailing slash.
But I like the idea of a category method on NSURL that implements some standards-based equivalence ("equivalence" is probably a better term than equality in this case).
@RobNapier refers to a related question with a good answer that points to RFC2616. Another relevant standard for url syntax is RFC1808.
The tough part is deciding what we mean by equivalence, for example, what about differing queries or fragments (anchor links)? The code below errs on the side of permissiveness for most of these ambiguities...
// 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;
}