brumbrum brumbrum - 5 months ago 56
Swift Question

can't get UIImage's init(contentsOfFile:) to work

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

Answer

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

Comments