【问题标题】:List saved files in iOS documents directory in a UITableView?在 UITableView 的 iOS 文档目录中列出保存的文件?
【发布时间】:2012-01-12 16:10:14
【问题描述】:

我已经设置了以下代码来将文件保存到文档目录:

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];

但是,我希望在成功保存后将每个文件添加到 UITableView。当点击 UITableView 中的文件时,我希望 UIWebView 导航到该文件(全部脱机)。

另外 - 我怎样才能得到文件名和结尾,例如“logo.png”而不是http://www.reddexuk.com/logo.png

我该怎么做?

【问题讨论】:

    标签: iphone objective-c ios xcode afnetworking


    【解决方案1】:

    这是我用来获取目录内容的方法。

    -(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;
    }
    

    【讨论】:

    • 谢谢,但是如何将这些数据放入 UITableView,然后在 UIWebView 中打开文件?
    • 这是一个很好的UITableView 教程,这里是指向本教程的xcode project 的链接。这是UIWebView的一个很好的教程
    • 谢谢。我知道如何创建 UITableView 等,但不确定如何将文件实际放入 UITableView 本身。您发送的网站也没有真正提及:(
    • 假设填充表格视图的数组称为“tableArray”,并且代码与表格在同一个类文件中。 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; tableArray = [self listFileAtPath:documentsDirectory];
    • 谢谢!那么我将在哪里发布此代码?您能否编辑您的答案以显示我如何将数据放入 UITableView(例如,将进入什么 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { )
    【解决方案2】:

    获取目录的内容

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

    获取最后一个路径组件,

    [[path pathComponents] lastObject]
    

    【讨论】:

    • 谢谢,但是如何将这些数据放入 UITableView,然后在 UIWebView 中打开文件?此外,“[[path pathComponents] lastObject]”不会仅获得文件类型的完整文件名(例如“.gif”而不是“test.gif”),那么我该怎么做才能获得“test.gif”?跨度>
    • 我建议阅读 UITableViews。 Stack Overflow 上不会有完整的教程
    • 但是@coneybeare - 您在回复有关文件类型的评论时没有提及任何内容。我也热衷于这样做。你能指出我正确的方向吗?
    • pathcomponents 在@"/" 上拆分,为您提供所需的内容。
    • directoryContentsAtPath 已弃用,请使用 contentsOfDirectoryAtPath
    【解决方案3】:
    -(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; }
    

    上面的例子是不言自明的。我希望它能回答你第二个问题。

    【讨论】:

    • 谢谢,但这不是我真正想要的。我不想找到多个文件名,我只想删除domain.com,所以最后留下“file.suffix”位。肯定有更快的方法吗?
    • @Mike Martin 你的回答给了我一个解决我现在面临的问题的想法。谢谢你。附言还有一件事,如果我需要添加可能具有以下集合扩展名的“匹配”文件(对象)怎么办:@“txt”,@“pdf”,@“doc”,@“rtf”,@ “png”,@“jpeg”?
    【解决方案4】:

    更合理的文件名:

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

    【讨论】:

      【解决方案5】:

      我知道这是一个老问题,但这是一个很好的问题,并且在 iOS 沙盒之后情况发生了变化。

      应用程序中所有可读/可写文件夹的路径现在包含一个哈希值,Apple 保留随时更改该路径的权利。它在每次应用启动时都会发生变化。

      您需要获取所需文件夹的路径,并且不能像过去那样对其进行硬编码。

      您请求文档目录,在返回数组中,它位于位置 0。然后从那里,您使用该值提供给 NSFileManager 以获取目录内容。

      下面的代码在 iOS 7 和 8 下工作,用于返回文档目录中的内容数组。您可能想根据自己的喜好对其进行排序。

      + (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;
      }
      

      【讨论】:

        【解决方案6】:

        谢谢亚历克斯,

        这里是 Swift 版本

        let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
        let documentDirectory = paths[0]
        if let allItems = try? FileManager.default.contentsOfDirectory(atPath: documentDirectory) {
            print(allItems)
        }
        

        【讨论】:

          【解决方案7】:
          NSDirectoryEnumerator *dirEnum = [[NSFileManager defaultManager] enumeratorAtPath:dir_path];
          
          NSString *filename;
          
          while ((filename = [dirEnum nextObject]))
          {
              // Do something amazing
          }
          

          用于枚举目录中的所有文件

          【讨论】:

            【解决方案8】:

            Swift 3.x

            let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
            if let allItems = try? FileManager.default.contentsOfDirectory(atPath: documentDirectory) {
              print(allItems)
            }
            

            【讨论】:

            • 如何从“文档/收件箱”中获取文件列表?并选择任何一个。
            【解决方案9】:

            斯威夫特 5

            返回 Documents 目录中所有 MP4/M4V 视频文件的 URL 数组的函数。如果您想要所有文件,只需删除 filter

            它只检查顶级目录中的文件。如果您还想列出子目录中的文件,请删除 .skipsSubdirectoryDescendants 选项。

            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 ?? []
            }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2014-09-10
              • 2015-07-19
              • 1970-01-01
              • 1970-01-01
              • 2015-12-05
              • 1970-01-01
              • 2016-09-16
              • 2017-11-22
              相关资源
              最近更新 更多