在 UITableView 中列出 iOS 文档目录中保存的文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8376511/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
List saved files in iOS documents directory in a UITableView?
提问by pixelbitlabs
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).
但是,我希望在成功保存每个文件后将其添加到 UITableView 中。当 UITableView 中的文件被点击时,我希望 UIWebView 导航到该文件(全部脱机)。
Also - how can I just get the filename and ending such as "logo.png" instead of http://www.reddexuk.com/logo.png?
另外 - 我怎样才能获得文件名和结尾,例如“logo.png”而不是http://www.reddexuk.com/logo.png?
How can I do this?
我怎样才能做到这一点?
回答by syclonefx
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;
}
回答by Mike Martin
-(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.
上面的例子是不言自明的。我希望它能回答你的第二个问题。
回答by coneybeare
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]
回答by DogCoffee
Thanks Alex,
谢谢亚历克斯,
Here is Swift version
这是 Swift 版本
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentDirectory = paths[0]
if let allItems = try? FileManager.default.contentsOfDirectory(atPath: documentDirectory) {
print(allItems)
}
回答by Alex Zavatone
I know this is an old question, but it's a good one and things have changed in iOS post Sandboxing.
我知道这是一个老问题,但这是一个好问题,iOS 沙盒后的情况发生了变化。
The path to all the readable/writeable folders within the app willnow have a hash in it and Apple reserves the right to change that path at any time. It willchange on every app launch for sure.
应用程序中所有可读/可写文件夹的路径现在将包含一个哈希值,Apple 保留随时更改该路径的权利。它肯定会在每次应用程序启动时发生变化。
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.
您请求文档目录,在返回数组中,它位于位置 0。然后,您使用该值提供给 NSFileManager 以获取目录内容。
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.
下面的代码在 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;
}
回答by mattt
For a more reasonable filename:
对于更合理的文件名:
NSString *filename = [[url lastPathComponent] stringByAppendingPathExtension:[url pathExtension]];
NSString *filename = [[url lastPathComponent] stringByAppendingPathExtension:[url pathExtension]];
回答by FertoVordalastr
NSDirectoryEnumerator *dirEnum = [[NSFileManager defaultManager] enumeratorAtPath:dir_path];
NSString *filename;
while ((filename = [dirEnum nextObject]))
{
// Do something amazing
}
for enumerating through ALL files in directory
用于枚举目录中的所有文件
回答by footyapps27
Swift 3.x
斯威夫特 3.x
let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
if let allItems = try? FileManager.default.contentsOfDirectory(atPath: documentDirectory) {
print(allItems)
}
回答by Marián ?erny
Swift 5
斯威夫特 5
Function that returns array of URLs of all files in Documents directory that are MP4 videos. If you want all files, just remove the filter
.
返回 Documents 目录中所有 MP4 视频文件的 URL 数组的函数。如果您想要所有文件,只需删除filter
.
It checks only files in the top directory. If you want to list also files in the subdirectories, remove the .skipsSubdirectoryDescendants
option.
它只检查顶级目录中的文件。如果您还想列出子目录中的文件,请删除该.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 {
##代码##.lastPathComponent.hasSuffix(".mp4")
}
return files ?? []
}