How to search files with specific extension in home directory of mac?

434 Views Asked by At

I want to search for files with doc extension in mac directory same as we are finding from finder using search command.

I'm using below code for doing this search. But it only searching from downloads directory. It is not searching from Document(Document directory of the finder, not application), Desktop or any of the other directories from Home directory.

NSString *docsDir = NSHomeDirectory();
NSFileManager *localFileManager=[[NSFileManager alloc] init];
NSDirectoryEnumerator *dirEnum =
    [localFileManager enumeratorAtPath:docsDir];

NSString *file;
while ((file = [dirEnum nextObject])) {
    strPath = [NSString stringWithFormat:@"%@/",NSHomeDirectory()];

    strPath = [strPath stringByAppendingString:file];
    NSLog(@"%@",strPath);

    NSArray *dirFiles = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:strPath error:nil];
    NSArray *pdfFiles = [dirFiles filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self ENDSWITH '.pdf'"]];

    NSLog(@"%@",pdfFiles);
}

I have tried to change the path to

NSString *docsDir = [NSString stringWithFormat:@"/Users/%@/",NSUserName()];

from

NSString *docsDir = NSHomeDirectory();

But still, the same thing happened.

I want to search for files with a specific extension in all directories like we are searching from finder as shown in below image.enter image description here

2

There are 2 best solutions below

0
On

To search like Finder does, use the MSMetadataQuery. This is the technology behind Spotlight:

https://developer.apple.com/documentation/foundation/nsmetadataquery

As for sandboxing, the MetadataQuery returns results and you'll then have to ask user for permission to read those files.

0
On

Isn't your application sandboxed (you can check by selecting your project and then capabilities) ?

I have run your code in both a sandboxed application, where it does not work, and in a non-sandboxed application, where it runs fine...

Why doesn't it run in a sandboxed application ?

  • From a sandboxed application it is the rule that you can't get access to Desktop etc. content,

  • From a sandboxed application, you get access to the Download directory though

BUT

enumeratorAtPath: does not traverse links - and in the Library/.../Data directory, Documents that you get from NSHomeDirectory(), Downloads is a link, so you will only get access to the first level of your Download folder.

  • @"/Users/%@/",NSUserName() will give you your "real" user document directory, but as your app is sandboxed, you would not be allowed to enumerate through it.

Looks like my assumption seems to explain pretty much all the symptoms you observe.