NSBundle.mainBundle().URLForResource("bach1", withExtension: "jpg")
Run Code Online (Sandbox Code Playgroud)
上面的代码返回null.
为了检查文件是否存在,我使用下面的代码:
let fileManager = NSFileManager.defaultManager()
if fileManager.fileExistsAtPath(savepath) {
println("exist")
}
Run Code Online (Sandbox Code Playgroud)
上面的代码返回该文件存在于目录中.
所以我不明白为什么第一个代码返回null
Leo*_*bus 12
你的问题是NSBundle.mainBundle().URLForResource("bach1",withExtension:"jpg")返回一个可选的NSURL.您需要使用if let打开它并从返回的URL中提取文件路径,如下所示:
if let resourceUrl = NSBundle.mainBundle().URLForResource("bach1", withExtension: "jpg") {
if NSFileManager.defaultManager().fileExistsAtPath(resourceUrl.path!) {
print("file found")
}
}
Run Code Online (Sandbox Code Playgroud)
Swift 3.x
if let resourceUrl = Bundle.main.url(forResource: "bach1", withExtension: "jpg") {
if FileManager.default.fileExists(atPath: resourceUrl.path) {
print("file found")
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11466 次 |
| 最近记录: |