ios - Swift 3.0 FileManager.fileExists(atPath :) always return false

标签 ios swift nsfilemanager

当我使用方法.fileExists(atPath:)判断文件是否存在于文件系统中时,该方法总是返回false给我。我检查了文件系统,文件确实存在。这是我的代码:

let filePath = url?.path
var isDir : ObjCBool = false
if(self.fileManager.fileExists(atPath: filePath!, isDirectory: &isDir)){
     let result = NSData(contentsOfFile: filePath!)
}

let filePath = url?.path
if(self.fileManager.fileExists(atPath: filePath!)){
     let result = NSData(contentsOfFile: filePath!)
}

if 子句将始终被跳过。

最佳答案

我假设您的 urlURL 类型。如果是这样,试试这个:

let filePath = url?.path  // always try to work with URL when accessing Files
if(FileManager.default.fileExists(atPath: filePath!)){  // just use String when you have to check for existence of your file
    let result = NSData(contentsOf: url!)  // use URL instead of String
}

说够了,你应该像这样改变你的实现:

if(FileManager.default.fileExists(atPath: (url?.path)!)){  // just use String when you have to check for existence of your file
    let result = NSData(contentsOf: url!)  // use URL instead of String
}

编辑:1

还有更好的方法,你可以称之为 swift-way (:D)。您不必显式检查文件是否存在

guard let result = NSData(contentsOf: fileURL) else {
    // No data in your fileURL. So no data is received. Do your task if you got no data
    // Keep in mind that you don't have access to your result here.
    // You can return from here. 
    return
}
// You got your data successfully that was in your fileURL location. Do your task with your result.
// You can have access to your result variable here. You can do further with result constant.
print(result)

没有 Objective-Cish NS 前缀的 Swift 3.0+ 更新:

do {
    let result = try Data(contentsOf: fileURL)
    print(result)
} catch {
    print(error)
}

关于ios - Swift 3.0 FileManager.fileExists(atPath :) always return false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42897844/

相关文章:

ios - 如何通过 Smooch SDK 将自定义数据与任何已发送的消息相关联?

ios - UIAccessibility 焦点与 UITabBarController

java - Firebase Auth - 复制修改后的用户登录名/电子邮件

ios - NSFileManager:试图删除文件,但它说它们不存在

ios - 调用可以抛出,但不能从属性初始值设定项中抛出错误

ios - 如何从 iOS 文档目录复制文本文件

iphone - iOS:如何停止设备待机定时器?

javascript - HTML 文本输入打破了 Iphone 6/7 plus 上的定位

ios - 如何在 UITextView 中设置文本边距?

swift - UILabel 如何成为 CALayer 并导致崩溃?