Getting a list of files in the Resources folder - iOS
Solution 1:
You can get the path to the Resources
directory like this,
NSString * resourcePath = [[NSBundle mainBundle] resourcePath];
Then append the Documents
to the path,
NSString * documentsPath = [resourcePath stringByAppendingPathComponent:@"Documents"];
Then you can use any of the directory listing APIs of NSFileManager
.
NSError * error;
NSArray * directoryContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsPath error:&error];
Note : When adding source folder into the bundle make sure you select "Create folder references for any added folders option when copying"
Solution 2:
Swift
Updated for Swift 3
let docsPath = Bundle.main.resourcePath! + "/Resources"
let fileManager = FileManager.default
do {
let docsArray = try fileManager.contentsOfDirectory(atPath: docsPath)
} catch {
print(error)
}
Further reading:
- NSFileManager class reference
- File System Programming Guide
- Error Handling docs
- Error Handling in Swift 2.0 blog post
- How to find the kind of errors a method may throw and catch them in Swift
Solution 3:
You can try this code also:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSError * error;
NSArray * directoryContents = [[NSFileManager defaultManager]
contentsOfDirectoryAtPath:documentsDirectory error:&error];
NSLog(@"directoryContents ====== %@",directoryContents);
Solution 4:
Swift version:
if let files = try? FileManager.default.contentsOfDirectory(atPath: Bundle.main.bundlePath ){
for file in files {
print(file)
}
}