Search code examples
iosuiwebviewnsurlnsfilemanager

How to compare a URL of "file://localhost/var/mobile/..." with "file:///var/mobile/..."


I'm opening a local file using UIWebView:loadRequest with an NSURLRequest which is in turn set from a URL.

The base location for url is obtained using:

    baseDirectory = [[NSFileManager defaultManager] URLForDirectory:NSApplicationSupportDirectory
                                                                        inDomain:NSUserDomainMask
                                                                appropriateForURL:nil   
                                                                            create: YES
                                                                            error:&err];

This returns a URL of the form:

file://localhost/var/mobile/Applications/Library/ApplicationSupport/ABC/XYZ/page.html

However when the UIWebViewDelegate shouldStartLoadForRequest:(NSURLRequest*) method gets called the NSURLRequest that is passed has changed to the following:

file:///var/mobile/Applications/Library/ApplicationSupport/ABC/XYZ/page.html

Both of these therefore reference the same file, however I have a situation where I need to make a comparison between the two (I needs to compare the /ABC/XYZ/page.html parts) and NSURL:isEqual returns NO when comparing the two.

Is there either: a) a method of NSFileManager that will return file:///var/mobile/... instead of file://localhost/var/mobile/...

or

b) easily extract just the /ABC/XYZ/page.html part and perform the comparison on that?


Solution

  • If you know that both files will always be on the same machine, then [[URL1 path] isEqualToString:[URL2 path]].


    The following unit tests pass:

    - (void)testURLPath
    {
        NSURL *URL = [NSURL URLWithString:@"file://localhost/foo/bar/baz"];
        NSString *path = [URL path];
        STAssertEqualObjects(path, @"/foo/bar/baz", nil);
    }
    
    - (void)testURLPathCompare
    {
        NSURL *URL1 = [NSURL URLWithString:@"file://localhost/foo/bar/baz"];
        NSURL *URL2 = [NSURL URLWithString:@"file:///foo/bar/baz"];
        NSString *path1 = [URL1 path];
        NSString *path2 = [URL2 path];
        STAssertTrue([path1 isEqualToString:path2], nil);
        STAssertTrue([[URL1 path] isEqualToString:[URL2 path]], nil);
    }