Re: Conversion from an absolute URL to relative
Re: Conversion from an absolute URL to relative
- Subject: Re: Conversion from an absolute URL to relative
- From: "Louis C. Sacha" <email@hidden>
- Date: Wed, 10 Mar 2004 01:54:48 -0800
Hello...
In order to work correctly for cases like
baseURLString = @"http://www.base.com/url/"
absoluteURLString = @"http://www.base.com/img/image.jepg"
The result relativeURL should be @"../img/image.jepg"
and others (where the last item in the base url is not a directory,
etc...), the code would have to be a bit more complex.
/* typed in mail, not tested, etc... */
- (NSString *)relativeURLStringForAbsoluteURLString:(NSString
*)absoluteURLString withBaseURLString:(NSString *)baseURLString
{
if ((baseURLString)&&(![baseURLString isEqualToString:@""])
{
/* make sure that baseURLString ends in a directory */
if (![[baseURLString
substringFromIndex:([baseURLString length] - 1)]
isEqualToString:@"/"])
{
/* note: doing this doesn't change the actual
string that was passed in, it changes the string that the method's
baseURLString pointer points to, and has no effect outside of this
method's scope */
baseURLString = [NSString
stringWithFormat:@"%@/",[baseURLString
stringByDeletingLastPathComponent]];
}
NSString *commonString = [absoluteURLString
commonPrefixWithString:baseURLString options:NSLiteralSearch];
if ((commonString)&&(![commonString isEqualToString:@""]))
{
/* make sure that the common url path ends in
a directory */
if (![[commonString
substringFromIndex:([commonString length] - 1)] isEqualToString:@"/"])
{
commonString = [NSString
stringWithFormat:@"%@/",[commonString
stringByDeletingLastPathComponent]];
}
NSString *remainderString;
if ([commonString
isEqualToString:absoluteURLString]) {remainderString = @"";}
else
{
NSRange commonRange =
[absoluteURLString rangeOfString:commonString];
remainderString = [absoluteURLString
substringFromIndex:commonRange.length];
}
/* add ../ to back up to parent directory as
many times as required */
while (![commonString isEqualToString:baseURLString])
{
baseURLString = [NSString
stringWithFormat:@"%@/",[baseURLString
stringByDeletingLastPathComponent]];
remainderString = [NSString
stringWithFormat:@"../%@",remainderString]];
}
return remainderString;
}
}
/* no baseURLString, empty base url, or base url does not match */
return absoluteURLString;
}
Please remember that this was typed up in mail and I can't test it at
the moment, so there may be errors either in typing or in logic. It
should at least give you a general idea of what you could do by
working with the strings to get the relative url, even if it doesn't
work perfectly (or at all).
Hope that helps,
Louis
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.