List all file from local directory
Sometimes we need to show all stored file in the application so a user can easily see their file or can delete this file also.Here I have taken the example of showing pdf file and delete this file.
Steps are.
1: List all stored file.
1 2 3 4 |
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSArray * directoryContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:&error]; |
2: here I am listing only pdf file.
1 2 3 4 5 6 |
for (int i = 0;i<directoryContents.count;i++){ NSString *data = directoryContents[i]; if ([data containsString:@".pdf"]){ invoiceListData[i] = data; } } |
3: For deleting the file.
1 2 3 4 5 6 7 8 |
NSString *fileName = [invoiceListData objectAtIndex:[indexPath row]]; NSFileManager *fileManager = [NSFileManager defaultManager]; NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *filePaths = [documentsPath stringByAppendingPathComponent:fileName]; NSError *error; BOOL success = [fileManager removeItemAtPath:filePaths error:&error]; |