58

I have set up the following code to save a file to the documents directory:

NSLog(@"Saving File...");

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.reddexuk.com/logo.png"]];
AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc] initWithRequest:request] autorelease];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"logo.png"];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Successfully downloaded file to %@", path);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

[operation start];

However, I wish to add each file to a UITableView when it is successfully saved. When the file in the UITableView is tapped, I'd like a UIWebView to navigate to that file (all offline).

Also - how can I just get the filename and ending such as "logo.png" instead of http://www.reddexuk.com/logo.png?

How can I do this?

pixelbitlabs
  • 1,934
  • 6
  • 36
  • 65

9 Answers9

145

Here is the method I use to get the content of a directory.

-(NSArray *)listFileAtPath:(NSString *)path
{
    //-----> LIST ALL FILES <-----//
    NSLog(@"LISTING ALL FILES FOUND");

    int count;

    NSArray *directoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:NULL];
    for (count = 0; count < (int)[directoryContent count]; count++)
    {
        NSLog(@"File %d: %@", (count + 1), [directoryContent objectAtIndex:count]);
    }
    return directoryContent;
}
syclonefx
  • 2,830
  • 1
  • 21
  • 24
  • thanks, but how do I put this data into a UITableView and then open the file in UIWebView? – pixelbitlabs Dec 04 '11 at 16:25
  • 1
    Here is a good [UITableView](http://www.iosdevnotes.com/2011/10/uitableview-tutorial/) tutorial and here is the link to the [xcode project](https://github.com/cwalcott/UITableView-Tutorial) for this tutorial. Here is a good tutorial on [UIWebView](http://www.iphonesdkarticles.com/2008/08/uiwebview-tutorial.html) – syclonefx Dec 04 '11 at 16:44
  • Thanks for that. I know how to create a UITableView etc but not sure how to get the files actually into the UITableView itself. The site you sent doesn't really mention that either :( – pixelbitlabs Dec 04 '11 at 16:56
  • 2
    Just assuming that your array to fill your table view is called "tableArray" and the code is in the same class file as your table. `NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; tableArray = [self listFileAtPath:documentsDirectory];` – syclonefx Dec 04 '11 at 20:56
  • thanks! So where would I post this code? Would you be able to edit your answer to show how I can put the data into the UITableView (for example, what would go in - **(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {** ) – pixelbitlabs Dec 05 '11 at 06:13
  • I put that code in my viewDidLoad method and an error came up - http://file.reddexuk.com/2W0k3J031J400j3T0g0P – pixelbitlabs Dec 05 '11 at 06:18
21
-(NSArray *)findFiles:(NSString *)extension{

NSMutableArray *matches = [[NSMutableArray alloc]init];
NSFileManager *fManager = [NSFileManager defaultManager];
NSString *item;
NSArray *contents = [fManager contentsOfDirectoryAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] error:nil];

// >>> this section here adds all files with the chosen extension to an array
for (item in contents){
    if ([[item pathExtension] isEqualToString:extension]) {
        [matches addObject:item];
    }
}
return matches; }

The example above is pretty self-explanatory. I hope it answers you second question.

Mike Martin
  • 376
  • 2
  • 7
  • Thanks but that's not what I was really asking for. I don't want to find multiple file names, I just want to cut out the http://www.domain.com/ so i'm left with the "file.suffix" bit at the end. Surely there's a quicker way to do that? – pixelbitlabs Dec 04 '11 at 16:40
  • @Mike Martin your answer gave me an idea to solve a problem I am facing right now. Thank you. P.S. Just one more thing, what if I need to add in "matches" files (objects) that might have an extension from the following set: @"txt", @"pdf", @"doc", @"rtf", @"png", @"jpeg"? – eugen Apr 11 '16 at 13:44
11

To get the contents of a directory

- (NSArray *)ls {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSArray *directoryContent = [[NSFileManager defaultManager] directoryContentsAtPath: documentsDirectory];

    NSLog(@"%@", documentsDirectory);
    return directoryContent;
}

To get the last path component,

[[path pathComponents] lastObject]
coneybeare
  • 33,113
  • 21
  • 131
  • 183
  • thanks, but how do I put this data into a UITableView and then open the file in UIWebView? Also, "[[path pathComponents] lastObject]" wouldn't get the full filename just the file type (e.g. ".gif" not "test.gif") so what can I do to get "test.gif"? – pixelbitlabs Dec 04 '11 at 16:26
  • 2
    I suggest reading up on UITableViews. A full length tutorial is not really gonna happen on Stack Overflow – coneybeare Dec 04 '11 at 16:29
  • but @coneybeare - you did not mention anything in reply to the comment about filetypes. I am also keen to do this. Can you point me in the right direction please? – pixelbitlabs Dec 04 '11 at 17:39
  • 2
    pathcomponents splits on @"/" giving you what you want. – coneybeare Dec 04 '11 at 18:27
  • 1
    `directoryContentsAtPath` is deprecated, use `contentsOfDirectoryAtPath` – SwiftArchitect Jul 04 '14 at 00:02
  • This answer was written in 2010 – coneybeare Jul 04 '14 at 11:43
8

Thanks Alex,

Here is Swift version

let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentDirectory = paths[0]
if let allItems = try? FileManager.default.contentsOfDirectory(atPath: documentDirectory) {
    print(allItems)
}
Simon Bengtsson
  • 7,573
  • 3
  • 58
  • 87
DogCoffee
  • 19,820
  • 10
  • 87
  • 120
6

I know this is an old question, but it's a good one and things have changed in iOS post Sandboxing.

The path to all the readable/writeable folders within the app will now have a hash in it and Apple reserves the right to change that path at any time. It will change on every app launch for sure.

You'll need to get the path to the folder you want and you can't hardcode it like we used to be able to do in the past.

You ask for the documents directory and in the return array, it's at position 0. Then from there, you use that value to supply to the NSFileManager to get the directory contents.

The code below works under iOS 7 and 8 to return an array of the contents within the documents directory. You may want to sort it according to your own preferences.

+ (NSArray *)dumpDocumentsDirectoryContents {

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [paths objectAtIndex:0];

    NSError *error;
    NSArray *directoryContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsPath error:&error];

    NSLog(@"%@", directoryContents);
    return directoryContents;
}
Alex Zavatone
  • 4,106
  • 36
  • 54
4

For a more reasonable filename:

NSString *filename = [[url lastPathComponent] stringByAppendingPathExtension:[url pathExtension]];

mattt
  • 19,544
  • 7
  • 73
  • 84
3

Swift 5

Function that returns array of URLs of all files in Documents directory that are MP4/M4V videos. If you want all files, just remove the filter.

It checks only files in the top directory. If you want to list also files in the subdirectories, remove the .skipsSubdirectoryDescendants option.

func listVideos() -> [URL] {
    let fileManager = FileManager.default
    let documentDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]

    let files = try? fileManager.contentsOfDirectory(
        at: documentDirectory,
        includingPropertiesForKeys: nil,
        options: [.skipsSubdirectoryDescendants, .skipsHiddenFiles]
    ).filter {
        ["mp4", "m4v"].contains($0.pathExtension.lowercased())
    }

    return files ?? []
}
Marián Černý
  • 15,096
  • 4
  • 70
  • 83
2
NSDirectoryEnumerator *dirEnum = [[NSFileManager defaultManager] enumeratorAtPath:dir_path];

NSString *filename;

while ((filename = [dirEnum nextObject]))
{
    // Do something amazing
}

for enumerating through ALL files in directory

1

Swift 3.x

let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
if let allItems = try? FileManager.default.contentsOfDirectory(atPath: documentDirectory) {
  print(allItems)
}
footyapps27
  • 3,982
  • 2
  • 25
  • 42