无法让 UIImage 的 init(contentsOfFile:) 工作

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

我试图在我的包的子目录的子目录中找到一个文件。我用这段代码创建了一个 init(contentsOfFile:).

的 UIImage
let resource = NSBundle.mainBundle().pathForResource("1g", ofType: "jpg", inDirectory: "Level1")      
let image = UIImage(contentsOfFile: resource!)

我做错了什么?

编辑:

这是有效的,因为您在 xcode 编辑器中创建的组不会影响实际路径。

let resource = NSBundle.mainBundle().pathForResource("1g", ofType: "jpg", inDirectory: nil)

let resource = NSBundle.mainBundle().pathForResource("1g", ofType: "jpg")

你收到错误致命错误:在展开可选值时意外发现 nil,这意味着 你的变量设置为 nil,但你的代码是希望它不会为零。

喜欢检查资源是否包含价值。

let resource = NSBundle.mainBundle().pathForResource("1g", ofType: "jpg", inDirectory: "Level1") 打印(资源) //

然后

喜欢

选择-1

if let resource = NSBundle.mainBundle().pathForResource("1g", ofType: "jpg", inDirectory: "Level1") 

{
  let image = UIImage(contentsOfFile: resource!)
}
else
 {
 print (resource)
 }

选择-2

let resource = NSBundle.mainBundle().pathForResource("1g", ofType: "jpg", inDirectory: "Level1")      

if resource != nil {
//Do Something
let image = UIImage(contentsOfFile: resource!)
}

额外 information

好的,我明白了。根据 Fatti Khan 提到的路径,我尝试了

let resource = NSBundle.mainBundle().pathForResource("1g", ofType: "jpg",inDirectory: nil)

相同
let resource = NSBundle.mainBundle().pathForResource("1g", ofType: "jpg")

似乎即使我在 xcode 编辑器中创建了组,但对实际路径没有影响,即:file:///Users/user/Desktop/MattNeuburg/pathFinder/pathFinder/1g.jpg。 pathFinder 是项目的名称。