Get all file names starting with a prefix from Resource folder

前端 未结 2 674
生来不讨喜
生来不讨喜 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.)

提交回复
热议问题