I'm making an app with the folder like image below:
As you can see in this picture, Stickers folder have 2 sub folder "1" and "2". In side them is bunch of icon and I wanna load it in a collection view with each sub folder is a package of different sticker. For more details, please see this picture:
So, how can I get it in my project folder? I've read about access document directory but seem like it not solve my problem.
Please help me. Thanks in advance.
Look at Filemanagers API. It offers all you need.
Example to get content at path:
let pathToDir1 = Bundle.main.resourcePath! + "/Stickers/1";
let fileManager = FileManager.default
let contentOfDir1 = try! fileManager.contentsOfDirectory(atPath: pathToDir1)
Example to iterate over:
let docsPath = Bundle.main.resourcePath!
let enumerator = fileManager.enumerator(atPath:docsPath)
let images = [UIImage]()
while let path = enumerator?.nextObject() as! String {
let contentOfCurDir = try! fileManager.contentsOfDirectory(atPath: path)
// do whatever you need.
}
For details see Apples documentation and sample code.
If you're looking to access an image within your project folder you simply need to use the image name. You don't need to define the whole path.
Objective-C
UIImage *img = [UIImage imageWithName:#"IMAGE_NAME"];
swift
var img = UIImage(named:"IMAGE_NAME")
Related
I have one JSON which contain path of images from one local folder of Project as Followed
The issue is i want to get image from that path, How do i achieve it?
I had try to convert String to URL and set URL as Image using Kingfisher Library
let url = URL(string: "/VWiOSProjects/CollageMakerDemo/Development/CollageMaker/CollageMaker/Goodies.xcassets/Goodies-1.imageset/Goodies-1.png")!
cell.imgTool.kf.setImage(with: url)
But it don't work I had Tried this one also
let url = URL(string: "/VWiOSProjects/CollageMakerDemo/Development/CollageMaker/CollageMaker/Goodies.xcassets/Goodies-1.imageset/Goodies-1.png")!
let imageData:NSData = NSData(contentsOf: url)!
let image = UIImage(data: imageData as Data)
cell.imgTool.image = image
NOTE: I can't upload this JSON file on Server, I need to use it Locally
I have solved my issue using fileURLWithPath
let url = URL.init(fileURLWithPath: "/VWiOSProjects/CollageMakerDemo/Development/CollageMaker/CollageMaker/Goodies.xcassets/Goodies-1.imageset/Goodies-1.png")
let imageData:NSData = NSData(contentsOf: url)!
let image = UIImage(data: imageData as Data)
cell.imgTool.image = image
If the images are in Assets(*.xcassets) folder, the you can access it by init(named:) method.
cell.imgTool.image = UIImage(named: "img1")
Actually you no need to store the entire path. You could store image names in array or something.
In my point of view, the best way is to add All Images to *.xcassets folder.(Because you have preloaded 5-10 images)
In case you needs to display it in collection view or TableView,
let imageName = "Goodies-\(indexPath.row)"
cell.imgTool.image = UIImage(named: imageName)
If images are in assets folder itself then go for #Lal Krishna's method. And if they are on server then you should add http:// or https:// and the URL of server followed by JSON's URL.
If still you are not getting it then let me know.
well am trying this :
if let storedCoverImagePath = UC.coverImagePath{
let storedCoverImage = UIImage(contentsOfFile: storedCoverImagePath as String)
self.coverImage.image = storedCoverImage
self.backgroundImageView.image = storedCoverImage
}
and the value of storedCoverImagePath is :
/Users/remy/Library/Developer/CoreSimulator/Devices/D29D4F6F-E146-419D-B4B8-B1914F56569F/data/Containers/Data/Application/637675BB-EFA1-A8RT-8B73-A3628/DocumentsCoverImage.jpg
its straight forward that am trying to get an image from this storedCoverImagePath path. i double checked the path, image is there still am not able to set the image using this path, is there is something that am missing if yes than tell me please
You have to specify path relative to your apps bundle or directory. If you hardcode the path like you did:
/Users/remy/Library/Developer/CoreSimulator/Devices/D29D4F6F-E146-419D-B4B8-B1914F56569F/data/Containers/Data/Application/637675BB-EFA1-A8RT-8B73-A3628/DocumentsCoverImage.jpg
it gets ignored because of the sandboxing. iOS does not allow the app to reference directories external to the sandbox.
Possible solutions
One way to get it working is to add the image to the project. Then you can get it using:
let image : UIImage = UIImage(named:"ImageName")
Another way, if the image is saved in documents directory of your app, is to use:
let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
let fileURL = documentsURL.URLByAppendingPathComponent(yourImageName)
let image = UIImage(contentsOfFile: fileURL.path!)
I need to be able to reference a file which is stored in my Xcode project in the following way:
I want to be able to use files which I have stored inside of the "data" folder.
How do I reference it to be able to read its contents? What is it's directory path?
I just figured it out. The apple swift documentation and other developer references are really unclear about it.
The way you would reference the "data" folder so as to scan the entire contents is by writing the following:
let path = NSBundle.mainBundle().resourcePath?.stringByAppendingPathComponent("data")
var error: NSError?
let filesInDirectory: [String]! = fileManager.contentsOfDirectoryAtPath(path!, error: &error) as? [String]
This will return the contents of the files in the "data" folder as an array of filenames.
Hope this helps :)
Relative to swift 3
let bundleURL = Bundle.main.bundleURL
let dataFolderURL = bundleURL.appendingPathComponent("data")
let fileURL = dataFolderURL.appendingPathComponent("file.txt")
print(fileURL.path)
print(FileManager.default.fileExists(atPath: fileURL.path))
let bundleURL = NSBundle.mainBundle().bundleURL
let dataFolderURL = bundleURL.URLByAppendingPathComponent("data")
let fileURL = dataFolderURL.URLByAppendingPathComponent("fileName.txt")
I'm working on an custom emoji keyboard in Swift and I'm having trouble finding and counting the images in a folder reference called "emojis".
EDIT: To clarify my issue is that let contents always end up as nil.
The structure from the location of the .xcodeproj file looks like this:
EmojiBoard/emojis/emoji-0.png and so on.
I've been trying to use the NSFileManager with no luck.
let fileManager = NSFileManager.defaultManager()
let contents = fileManager.contentsOfDirectoryAtPath("emojis", error: &error)
println(contents)
This prints nil. I've also tried "EmojiBoard/emojis" and "/EmojiBoard/emojis".
I need this to determine how many images there are and loop them all out without having to resort to an insane switch statement or something like that.
Thank you!
P.S. Please note that I'm coding in Swift, not Objective C. I'm not proficient enough to convert C programming to swift I'm afraid. D.S.
if you created folder reference when adding the folder to your project use it like this (emojis folder icon is a blue folder):
let resourceURL = Bundle.main.resourceURL!.appendingPathComponent("emojis")
var resourcesContent: [URL] {
(try? FileManager.default.contentsOfDirectory(at: resourceURL, includingPropertiesForKeys: nil)) ?? []
}
let emojiCount = resourcesContent.count
print(emojiCount)
if you created groups when adding the folder to your project use it like this (emojis folder icon is a yellow folder):
let resourceURL = Bundle.main.resourceURL!
let resourcesContent = (try? FileManager.default.contentsOfDirectory(at: resourceURL, includingPropertiesForKeys: nil)) ?? []
let emojiCount = resourcesContent.filter { $0.lastPathComponent.hasPrefix("emoji-") }.count
print(emojiCount)
From the top of my head, without access to an IDE to test this code, I reckon something like this:
let fileManager = NSFileManager.defaultManager()
let contents = fileManager.contentsOfDirectoryAtPath(path, error: &error)
for var index = 0; index < contents.count; ++index {
println("File is \(contents[index])")
}
If you replace 'path' above with your documents directory, this code should loop through the whole folder and print out all files.
If you just want the count of items just do this:
println("count is \(contents.count)")
The problem (or at least a major part of the problem) is your path. You can't pass in a path that's just a filename. You need an absolute path to one of the sandboxed directories available to your app like the documents directory.
Your code might look like this:
let documentsDir = NSSearchPathForDirectoriesInDomains(
NSSearchPathDirectory.DocumentDirectory,
NSSearchPathDomainMask.UserDomainMask,
true)[0] as! NSString
let emojisPath = documentsDir.stringByAppendingPathCompnent("emojis")
let contents = fileManager.contentsOfDirectoryAtPath(emojisPath,
error: &error)
println(contents)
(That would work if your emojis folder is in your app's documents folder. If instead your emojis are in your app bundle (built into the app) you would need to use different code entirely (using NSBundle functions to get a path to the directory inside the bundle).
EDIT:
If you want to find files in your app's bundle use the NSBundle method resourcePath, and then append the folder name to the bundle's resourcePath using stringByAppendingPathCompnent, like the code above.
I have bunch of tile images inside the folder called "Tiles"
I need to extract one image at a time from that folder, and set it to UIView object.
I am stuck on how to get the image from inside that folder.
Can anyone help do this in Swift?
If you have the image name,you can just access the image in this folder like this
let image = UIImage(named: "image.png")
Or this
let imageURL = NSBundle.mainBundle().URLForResource("image", withExtension: "png")
let image = UIImage(contentsOfFile: imageURL!.path!)
If you want get all images,you create a real folder inside the project
let imageArray = NSBundle.mainBundle().URLsForResourcesWithExtension("png", subdirectory: "Titles") as! [NSURL]
This will return an urlArray of png inside Titles folder.You can use contentsOfFile as show before to access image