Get all file names starting with a prefix from Resource folder

前端 未结 2 673
生来不讨喜
生来不讨喜 2021-02-08 13:02

How can we get all file names starting with a prefix from resource folder..

相关标签:
2条回答
  • 2021-02-08 14:02

    Updated for Swift 4.0:

    In my case, I was looking for files that began with fileName-1.png where there might be other files with the fileName prefix.

    1) I thought about using regex, but splitting the string was faster and easier, so I went that route to get the prefix.

    let myKnownFileNameString = "fileName-1.png"
    let filePrefix = myKnownFileNameString.split(separator: "-").first
    

    2) Create an empty array to store images you find:

    var imageArray: [UIImage] = []
    

    3) Then, get the URLs from the bundle, filter them and map the URLs to UIImage instances:

    if let filePrefix = filePrefix, let fileURLs = Bundle.main.urls(forResourcesWithExtension: "png", subdirectory: nil) {
        imageArray = fileURLs.filter{ $0.lastPathComponent.range(of: "^\(filePrefix)", options: [.regularExpression, .caseInsensitive, .diacriticInsensitive]) != nil }
                             .map{ UIImage(contentsOfFile: $0.path)! }
    }
    

    From there, you've got an array of images that you can do stuff with (animate them in a UIImageView, etc.)

    0 讨论(0)
  • 2021-02-08 14:03

    You can achieve that adapting the following code:

    NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:
                      [[NSBundle mainBundle] bundlePath] error:nil];
    NSArray *pngs = [files filteredArrayUsingPredicate:
                     [NSPredicate predicateWithFormat:@"self ENDSWITH[cd] '.png'"]];
    NSLog(@"%@", pngs);
    

    Running this code you will see the list of PNG's on your bundle. Change the predicate to match with the prefix you want:

    NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:
                      [[NSBundle mainBundle] bundlePath] error:nil];
    NSArray *filesWithSelectedPrefix = [files filteredArrayUsingPredicate:
                                        [NSPredicate predicateWithFormat:@"self BEGINSWITH[cd] 'prefix'"]];
    NSLog(@"%@", filesWithSelectedPrefix);
    
    0 讨论(0)
提交回复
热议问题