How to find out if the NSURL is a directory or not

前端 未结 5 2224
萌比男神i
萌比男神i 2020-12-14 09:31

I have a NSURL object. It has address of a filesystem element, it is either a file or a directory. I want to be able to tell if the NSURL is a directory or a file.

I

5条回答
  •  感动是毒
    2020-12-14 10:10

    If you know the file URL has been standardized, then you can test for a trailing slash.

    -URLByStandardizingPath will standardize a file URL including ensuring a trailing slash if the path is a directory.

    Here is a test which shows -URLByStandardizingPath adding the trailing slash:

    // Get a directory, any directory will do
    NSURL *initialURL = [[NSBundle mainBundle] bundleURL];
    NSString *initialString = [initialURL absoluteString];
    
    // String the trailing slash off the directory
    NSString *directoryString = [initialString substringToIndex:[initialString length] - 1];
    NSURL *directoryURL = [NSURL URLWithString:directoryString];
    
    XCTAssertFalse([[directoryURL absoluteString] hasSuffix:@"/"],
                   @"directoryURL should not end with a slash");
    
    XCTAssertTrue([[[directoryURL URLByStandardizingPath] absoluteString] hasSuffix:@"/"],
                  @"[directoryURL URLByStandardizingPath] should end with a slash");
    

    As you can see, [[[directoryURL URLByStandardizingPath] absoluteString] hasSuffix:@"/"] is the test.

提交回复
热议问题