0

I have a few data files like

AAA.plist
BBB.plist
CCC.plist

I would like to get the list of these plist file. If I know the file name in advance, I can get the file like this.

 let path : String = Bundle.main.path(forResource: "AAA", ofType: "plist")!
 var qplist = NSArray(contentsOfFile: path)

However I want to get the plist file list in case of not knowing the file name in advance.

Nirav D
  • 71,513
  • 12
  • 161
  • 183
whitebear
  • 11,200
  • 24
  • 114
  • 237

2 Answers2

2

You can use urls(forResourcesWithExtension:subdirectory:) for that.

if let urls = Bundle.main.urls(forResourcesWithExtension: "plist", subdirectory: nil) {

     print(urls)
}
//Set subdirectory with specific name instead of nil if files inside some directory.

You can also use paths(forResourcesOfType:inDirectory:) to get array of paths.

Nirav D
  • 71,513
  • 12
  • 161
  • 183
  • 1
    FYI - Note that the files will only be in a subdirectory if the folder in your Xcode project is blue and not yellow. – rmaddy May 23 '17 at 05:07
  • Yes, whitebear @rmaddy is correct set `subdirectory` only if folder color is blue not yellow. – Nirav D May 23 '17 at 05:09
  • Thanks Nirav D and thanks rmaddy for your advice. Xcode group/folder system is quite confusing to me.... – whitebear May 23 '17 at 06:21
  • @whitebear Welcome mate :) – Nirav D May 23 '17 at 06:23
  • It works with subdirectory, however is it possible to use group instead of subdirectory??? I would like to pick the plist files under a certain group – whitebear May 23 '17 at 06:46
  • @whitebear group will not create directory it will just use to manage view in Xcode if you check in location there is no directory with that group name, So you need to add the sub directory name not the group name also if it is with main project then `nil` will also works – Nirav D May 23 '17 at 06:49
  • @Nirav D I see.... it I just wonder why group/folder system is very complex and which I should use. And If I use subdirectory system here, I need to access each files another place, I also check this article you edit and learning, thank you very much https://stackoverflow.com/questions/40692737/how-to-get-path-to-a-subfolder-in-main-bundle – whitebear May 23 '17 at 09:23
0

Use the enumerator from FileManager:

let path = Bundle.main.resourcePath
let man = FileManager.default

for file in man.enumerator(atPath: path!)! {
    print(file)
}
David Berry
  • 40,941
  • 12
  • 84
  • 95