【问题标题】:can't get UIImage's init(contentsOfFile:) to work无法让 UIImage 的 init(contentsOfFile:) 工作
【发布时间】:2015-11-12 09:17:03
【问题描述】:

我试图在我的包的子目录的子目录中找到一个文件。我使用这段代码创建了一个带有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")

【问题讨论】:

  • 无法获取资源。所以通过正确的路径。右键单击1g.jpg并在finder中显示,然后将项目名称后的路径粘贴到“inDirectory:????”中?标记位置
  • 我的完整路径:file:///Users/user/Desktop/MattNeuburg/pathFinder/pathFinder/1g.jpg 我尝试了 pathFinder/1g.jpg、pathFinder、pathFinder/pathFinder。没有工作:/
  • 您能通过 Dropbox 或其他方式分享您的项目,以便我看看吗?
  • 刚刚想通了..

标签: ios swift uiimage


【解决方案1】:

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

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

让资源 = 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

【讨论】:

  • @krompir2 -- 你的编码是正确的,检查一下你的目录是否正确,我给了参考链接检查一次,你明白了
  • 我检查了链接,不,它仍然无法正常工作。我也使用了这种方法: let resource2 = NSBundle(forClass: self.dynamicType).pathForResource("1g", ofType: "jpg", inDirectory: "CustomAssets/Level1/")
  • 你是对的,但没有得到答案,好吧,首先检查所有子目录然后把上面的行放在上面
  • 看起来组对实际路径没有影响
  • 哈哈,好的,在你的更新问题 where.in which line get the error
【解决方案2】:

好的,我想通了。根据 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 是项目的名称。

【讨论】:

    猜你喜欢
    • 2020-05-18
    • 2016-08-05
    • 1970-01-01
    • 1970-01-01
    • 2017-05-03
    • 1970-01-01
    • 1970-01-01
    • 2020-02-23
    • 2014-12-26
    相关资源
    最近更新 更多