Reputation: 4589
I am trying to locate a file in a subdirectory of subdirectory of my bundle. I used this code to create an UIImage with init(contentsOfFile:)
.
let resource = NSBundle.mainBundle().pathForResource("1g", ofType: "jpg", inDirectory: "Level1")
let image = UIImage(contentsOfFile: resource!)
What am I doing wrong?
EDIT:
This works because groups you create in xcode editor do not affect the actual path.
let resource = NSBundle.mainBundle().pathForResource("1g", ofType: "jpg", inDirectory: nil)
or let resource = NSBundle.mainBundle().pathForResource("1g", ofType: "jpg")
Upvotes: 0
Views: 776
Reputation: 82759
you are get the error fatal error: unexpectedly found nil while unwrapping an Optional value, this means your variable is set to nil, but your code is expecting it to not be nil.
do like check the resource contains value or not.
let resource = NSBundle.mainBundle().pathForResource("1g", ofType: "jpg", inDirectory: "Level1") print (resource) //
then
do like
Choice -1
if let resource = NSBundle.mainBundle().pathForResource("1g", ofType: "jpg", inDirectory: "Level1")
{
let image = UIImage(contentsOfFile: resource!)
}
else
{
print (resource)
}
Choice -2
let resource = NSBundle.mainBundle().pathForResource("1g", ofType: "jpg", inDirectory: "Level1")
if resource != nil {
//Do Something
let image = UIImage(contentsOfFile: resource!)
}
for additional information
Upvotes: 1
Reputation: 4589
Ok I figured it out. Based on the path Fatti Khan mentioned I tried
let resource = NSBundle.mainBundle().pathForResource("1g", ofType: "jpg",inDirectory: nil)
which is the same as
let resource = NSBundle.mainBundle().pathForResource("1g", ofType: "jpg")
It seems that even though I created groups in xcode editor that had no effect no the actual path, which is: file:///Users/user/Desktop/MattNeuburg/pathFinder/pathFinder/1g.jpg
. pathFinder is the name of the project.
Upvotes: 0