我如何加载我的UITableView与列表中保存的文件在我的文档目录



如何在我的文档目录中加载我的UITableView中保存的文件列表?我只需要一个小的例子或一个简单的在线教程,因为我一直在拔我的头发。所有的文件都保存在iOS文档目录中我只需要在UITableView中列出它们

NSArray *filePathsArray;
- (void)setUpTheFileNamesToBeListed
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    filePathsArray = [[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory  error:nil];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [filePathsArray count];   
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    //Insert this line to add the file name to the list
    cell.textLabel.text = [documentsDirectory stringByAppendingPathComponent:[filePathsArray objectAtIndex:indexPath.row]];
}

从上面的两个答案中,您知道了如何从文档目录中检索文件。

现在您想知道当用户点击单元格时如何打开文件。

你只需要使用UITableView委托函数也就是

       -(void)tableView(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
        {
               //do all your file opening logic here.
               //your file data is stored in the NSArray myFileData(refer the previous answer posted above)
              //and suppose you want to fetch the data which is in the file, is of type NSURL, means the file data is just a URL link.
        //just declare a NSURL in your .h(say myURL) (synthesize it etc)

        myURL=[NSURL URLWithString:[myFileData objectAtIndex:indexPath.row]]
         }

现在你的myURL包含了存储在文件中的链接然后你可以在你的webView中使用那个url

您可以使用

获取文档目录的路径
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

您将使用

获得其中的文件列表
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:nil];

这个数组将包含目录和文件。枚举dirContents并使用

检查它是否是一个文件
- (BOOL)fileExistsAtPath:(NSString *)path

如果文件不存在,要么从dirContents中过滤出来,要么创建一个新的数组,其中只包含存在的文件的路径,并将其用作表视图的数据源。

最新更新