开发者

Get all file names starting with a prefix from Resource folder

开发者 https://www.devze.com 2023-02-16 04:47 出处:网络
How can we get all file names开发者_开发问答 starting with a prefix from resource folder.. You can achieve that adapting the following code:

How can we get all file names开发者_开发问答 starting with a prefix from resource folder..


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);


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

精彩评论

暂无评论...
验证码 换一张
取 消