Search code examples
swiftimageassets

Swift Images cannot be read in Asset Catalog


I'm trying to save some images into my bundle. The images reads just fine when I save them in the main bundle. in main bundle

However, if I place them into the asset catalog, they can no longer be read. In asset catelog

Below are the codes I use to access them. If I save the pictures inside the asset catalog, the for item in items loop doesn't pick up any of the pictures.

override func viewDidLoad() {
    super.viewDidLoad()

    let fm = FileManager.default
    let path = Bundle.main.resourcePath!
    let items = try! fm.contentsOfDirectory(atPath: path)

    for item in items {
        if item.hasPrefix("nssl") {
            pictures.append(item)
        }
    }
}

Solution

  • There's no documented way to iterate through the images contained in an xcasset file. At build time the assets get compiled to a .car file, but the only way to read images out of the asset is through UIImaged(named:).

    If you need to be able to iterate through some resources in this way, it's best to store them in a simple folder inside your bundle.