Reputation: 1934
How can I load my UITableView with a list of saved files in my documents directory? I just need a small example or a simple online tutorial as I've been pulling my hair out. All the files are saved to the iOS document directory and all I need to do is list them in my UITableView.
Upvotes: 0
Views: 3959
Reputation: 26390
You can get the path of the documents directory using
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
You will get the list of files in it using
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:nil];
This array will contain directories as well as files. Enumerate through dirContents and check if it is a file using
- (BOOL)fileExistsAtPath:(NSString *)path
If the file does not exist, either filter that out from the dirContents or else create a new array with paths of only the files that do exist and use that as a datasource for the table view.
Upvotes: 1
Reputation: 4254
From the above two answers you know how to retrieve the files from the document directory.
and Now you want how to open a file when a user tap on te cell.
you just have to use the UITableView delegate function i.e
-(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]]
}
now your myURL is having the link which is stored in the file and then you can use that url in your webView.
Upvotes: 1
Reputation: 6268
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]];
}
Upvotes: 3