4

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?

Fire Fist
  • 7,032
  • 12
  • 63
  • 109

2 Answers2

5

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'"
Wain
  • 118,658
  • 15
  • 128
  • 151
  • yes. However i also sorted by creationDate and can't filter with it. Is there any ways? – Fire Fist Jul 24 '13 at 14:31
  • Sort and filter are unrelated. How are you sorting and what problem do you see? – Wain Jul 24 '13 at 14:35
  • Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Can't do a substring operation with something that isn't a string (lhs = file://localhost/private/var/mobile/Applications/C72F3F4C-EBF0-4A74-879B-3219C7147479/Documents/Temp/ rhs = .txt)' – Fire Fist Jul 24 '13 at 14:38
  • @Yahiko, you may need to [convert the `NSURL` to a `NSString`](http://stackoverflow.com/questions/8082719/convert-an-nsurl-to-an-nsstring). You can't call `NSString` functions on an `NSURL`. – Marcus Adams Jul 24 '13 at 14:53
  • @MarcusAdams, you could, or use the predicate to get the `absoluteString` from the URL. – Wain Jul 24 '13 at 15:02
  • Yes , i used @"absoluteString ENDSWITH '.txt'" and still can't filter txt format. :( – Fire Fist Jul 24 '13 at 16:32
  • Can you log the contents of the array before you filter and show the code you're using to filter. – Wain Jul 24 '13 at 18:28
2

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.

Puneet Sharma
  • 9,369
  • 1
  • 27
  • 33