NSBundle.mainBundle().URLForResource("bach1",withExtension: "jpg")
上面的代码返回null.
为了检查文件是否存在,我使用下面的代码:
let fileManager = NSFileManager.defaultManager()
if fileManager.fileExistsAtPath(savepath) {
println("exist")
}
上面的代码返回该文件存在于目录中.
所以我不明白为什么第一个代码返回null
你的问题是NSBundle.mainBundle().URLForResource(“bach1”,withExtension:“jpg”)返回一个可选的NSURL.如果要打开它并从返回的URL中提取文件路径,则需要使用以下内容:
if let resourceUrl = NSBundle.mainBundle().URLForResource("bach1",withExtension: "jpg") {
if NSFileManager.defaultManager().fileExistsAtPath(resourceUrl.path!) {
print("file found")
}
}