Swift Images cannot be read in Asset Catalog - swift

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

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.

Related

SpriteKit in screensaver can't find images

I am making a screensaver in Swift using SpriteKit.
While testing screensaver in app, all the textures load properly. As soon as I make .saver and load it in System Preferences, SpriteKit shows that images are not found.
I used (imageNamed: ""), so I tried using
var imageURL = Bundle.main.url(forResource: "gradient", withExtension: "png")
let imageGradient = NSImage(contentsOf: imageURL!)!
,but I got the same result.
SpriteKit can't access images when built into .saver file, but works perfectly when ran through the app.
I have included images in bundle, in assets, in Target's Copy Bundle Resources/Development Assets/Resource Tags.
You can clone the project from here: https://github.com/Nazar-Bibik/SavePortal
I have looked into this project: https://github.com/leebradley/nyan-screensaver
And I found how to properly do it:
You need to put images into bundle, not xcassets ( put it with .swift files )
Instead of using image name use the following
let sourceBundle = Bundle(for: MainSwiftFile.self)
let imagePath = sourceBundle.path(forResource: "picture-name", ofType: "png")!
neededTextures = SKTexture(imageNamed: imagePath)
You need to provide the name of the .swift file with your principal class ( principle class in info.plist file ).
The rest is simple - forResource is a file name, ofType is a file extension and instead of passing usual name in imageNamed: you provide String of path to file.
"imagePath" is of a String type.

Load Multiple pList Files into a View

I am creating a quiz app and the data are in the pList.
I have multiple pLists representing different categories. I do not want to merge these pList into one single file because I will use them separately for another purpose.
My question is, can we read or load multiple pList files into a View at once? If yes, how?
I am using the following code to load single pList files:
let path = Bundle.main.path(forResource: "pListData", ofType: "plist")
let dict = NSDictionary(contentsOfFile: path!)
pListData = (dict!["Tips"]! as AnyObject) as? Array
I am presenting a single data (a question) from a single pList each time a question is loaded. How do you randomly read from multiple pList sources instead of from a single one?

Xcode Project Folder Structure

I am using the latest XCode / Swift 3.0 and facing some problems:
I created a folder in /MyProject/MyProject/Assets/Subfolder1 and stored a few hundred .txt files in it to iterate over the files inside the Subfolder1 with the following code:
let fm = FileManager.default
fm.enumerator(atPath: "/MyProject/Assets/Subfolder1")?.forEach({ (e) in
if let e = e as? String, let url = URL(string: e) {
doSomethingWith(url.pathExtension)
}
})
But I cannot find any files. I tried some variations ("/Assets/Subfolder1/" and "/MyProject/MyProject/Assets/Subfolder1"), all are not working.
What is the correct path that I have to specify?
Best
Chris
First off, make sure you have added the actual folder to the Xcode project. You can do this simply by dragging and dropping the folder into your project. After you drag and drop, this window should appear
Make sure you select Create folder references and Copy items if needed. This will make sure that the entire folder is constantly synced inside your Xcode project. Then to verify that the assets will be transferred to your device when building the project, go into Build Phases and then to Copy Bundle Resources and you should see the name of the folder, in my case, I have named it TextFiles.
Now because you have added your folder into the application's Main Bundle, you can access it by doing this:
let fm = FileManager.default
let path = Bundle.main.resourcePath?.appending("/TextFiles")
fm.enumerator(atPath: path!)?.forEach({ (e) in
if let e = e as? String, let url = URL(string: e) {
doSomethingWith(url.pathExtension)
}
})
The reason we need to do the Bundle.main.resourcePath before it and can't simply say /TextFiles is because if we say /TextFiles it looks for that folder starting from the system root, which is why it wasn't working before. It would be like having a folder in C:/Users/Abc123/Documents/TextFiles but the system is looking for it in C:/TextFiles.

Get number of images in xcasset

I want to programmatically load a couple of images into arrays from my xcassets. I don't know how many images there are in the asset, but the images are named in order, like this: "img1_1", "img1_2", "img2_1", "img2_2", ...
I put the images in folders inside the asset, so folder "images1" contains all images with names starting with "img1_" and the folder called "images2" contains all images starting with "img2_". Does that help?
How do I get the number of images in the asset that are named like that so I can iterate through them and add them to my array?
There isn't a real easy way to go about it since the files are placed in the app at compile time. You can, though, create a RunScript in the Build Phases to be ran before compiling that creates a text file of the images. Then you can read in that text file and populate an array of images. You can use that array to get the details you need.
RunScript in the Build Phases:
#!/bin/sh
>./your_app_folder/fileNames.txt
for FILE in ./your_app_folder/Images.xcassets/actions/*; do
echo $FILE >> ./your_app_folder/fileNames.txt
done
Also, here's a link to an accepted answer that a previous poster asked with more details.
Another option if you do not want to deal with Build Phases, and one I'd probably choose, is not to use the Assets.xcassets file. Just place the images in a folder within your app bundle. It's much easier to read from the bundle.
UPDATE:
For the second option, you can drag your images (or folder of images) to your project, but be sure copy as a folder reference rather than group. Then in your code, you can read that folder using the FileManager.
let fileManager = FileManager.default
let imagePath = Bundle.main.resourcePath! + "/your_new_folder"
let imageNames = try! fileManager.contentsOfDirectory(atPath: imagePath)
imageNames in this case will be an array of file names within that url path. If go this route, you probably have to load the images by contentsOfFile too.
if let imagePath = bundle.path(forResource: fileName, ofType: nil) {
myImage = UIImage(contentsOfFile: imagePath)
}

NSBundle.mainBundle().URLForResource("bach1", withExtension: "jpg") returning null

NSBundle.mainBundle().URLForResource("bach1", withExtension: "jpg")
The above code is returning null.
In order to check if the file exists or not, I used below code:
let fileManager = NSFileManager.defaultManager()
if fileManager.fileExistsAtPath(savepath) {
println("exist")
}
The above code returns that file exists in directory.
So I don't understand why the first code is returning null
Your problem is that NSBundle.mainBundle().URLForResource("bach1", withExtension: "jpg") returns an optional NSURL. You need to use if let to unwrap it and extract your file path from the returned url as follow:
if let resourceUrl = NSBundle.mainBundle().URLForResource("bach1", withExtension: "jpg") {
if NSFileManager.defaultManager().fileExistsAtPath(resourceUrl.path!) {
print("file found")
}
}
Swift 3.x
if let resourceUrl = Bundle.main.url(forResource: "bach1", withExtension: "jpg") {
if FileManager.default.fileExists(atPath: resourceUrl.path) {
print("file found")
}
}
I found that you have to actually go into Build Phases -> Copy Bundle Resources and manually add your item sometimes to the bundle. In my case it was a video file that didn't get added to the bundle correctly on its own.
NSBundle.URLForResource only returns files that are bundled in your application at build/compile time, like when you drag a file into your Xcode project and add it to your app target. You can typically use this when your app comes preloaded with resources you need, like images, movies, databases, and other files.
It seems like savepath is a path your application wrote to while running (maybe into your app's Documents directory?). Because of this, the file is outside of the bundle and you will need to store that path/URL somewhere (or build it up again) if you need to reference the file in the future.
I had this issue too. My fix was:
Selecting the file in project navigator
Open the 'File Inspector' (on the right hand side pane)
Checking the app target in the Target Membership