I'm trying to use Swift to iterate over the images I have put into my Assets folder. I'd like to iterate over them and insert them into a .nib
file later, but so far I cannot find how to get something like:
let assetArray = ["image1.gif", "image2.gif", ...]
Is this possible? I've been playing with NSBundle.mainBundle()
but couldn't find anything on this. Please let me know. Thanks!
xcassets Catalog in Xcode. An asset catalog, simply put, is a single folder in Xcode that you use to organize your app's images, icons, colors, and more. Instead of adding individual images to Xcode's file organizer, you add assets neatly organized in a single catalog.
Create a new file (⌘N) and select the Asset Catalog template in the iOS – Resource panel. Choose a name, select the targets that should include the catalog, and click “Create.” Select the new *. xcassets file in the project explorer.
Use of xcassets is the new standard as of Xcode 5 and iOS 7. Import images by clicking on the blue folder called "Images. xcassets" then click on the small "+" plus sign at the bottom of the window that appears. Now choose "Import" to put images in there.
Assets.xcassets is not a folder but an archive containing all the images using Assets.car as its filename.
If you really want to read the assets file then you need to use some library that can extract the contents of the file like this one.
Or you can create a bundle in your project and drag all the images you have there. In my case, I have Images.bundle in my project. To get the filenames you can do the following:
let fileManager = NSFileManager.defaultManager()
let bundleURL = NSBundle.mainBundle().bundleURL
let assetURL = bundleURL.URLByAppendingPathComponent("Images.bundle")
let contents = try! fileManager.contentsOfDirectoryAtURL(assetURL, includingPropertiesForKeys: [NSURLNameKey, NSURLIsDirectoryKey], options: .SkipsHiddenFiles)
for item in contents
{
print(item.lastPathComponent)
}
SWIFT 3/4 Version:
let fileManager = FileManager.default
let bundleURL = Bundle.main.bundleURL
let assetURL = bundleURL.appendingPathComponent("Images.bundle")
do {
let contents = try fileManager.contentsOfDirectory(at: assetURL, includingPropertiesForKeys: [URLResourceKey.nameKey, URLResourceKey.isDirectoryKey], options: .skipsHiddenFiles)
for item in contents
{
print(item.lastPathComponent)
}
}
catch let error as NSError {
print(error)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With