Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter file with extension from document directory in iOS?

Hello i am now retrieving file from document directory in iOS.

And also i sorted file by CreationDate.

In my document directory , it have also a lot of Folders and files.

So when i retrieve all files from document directory , that folders name are also including.

I only want to retrieve (.txt) format file.

How can i do that?

like image 221
Fire Fist Avatar asked Mar 23 '23 01:03

Fire Fist


2 Answers

Assuming all of the files have an extension, you can create a predicate and use it to filter the array. The predicate would have a format like:

@"self ENDSWITH '.txt'"

Based on your comment below, you actually have the full file NSURL, not string file names. So you should use the predicate format:

@"absoluteString ENDSWITH '.txt'"
like image 103
Wain Avatar answered Mar 25 '23 16:03

Wain


This is in addition to @Wain's answer and assuming that you are using a webview to load the text file

  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  NSString *documentsDirectory = [paths objectAtIndex:0];
  NSArray *filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory  error:nil];
  NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF EndsWith '.txt'"];
  filePathsArray =  [filePathsArray filteredArrayUsingPredicate:predicate];
  NSLog(@"files array %@", filePathsArray);
  NSString *localDocumentsDirectoryVideoFilePath = [documentsDirectory
                                                    stringByAppendingPathComponent:[filePathsArray objectAtIndex:0]];
  NSURL *fileUrl=[NSURL fileURLWithPath:
                   localDocumentsDirectoryVideoFilePath];
  [_webview loadRequest:[NSURLRequest requestWithURL:fileUrl]];

Here _webview is an IBOutlet. Also, it is loading the first text file.
I hope this helps.

like image 27
Puneet Sharma Avatar answered Mar 25 '23 17:03

Puneet Sharma