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

Dean Lee picture Dean Lee · Mar 20, 2017 · Viewed 23.1k times · Source

When I use method .fileExists(atPath:)to judge whether the file is exist in file system, the method always return false to me. I checked the file system and the file do exist. Here is my code:

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

or

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

the if clause will always be skipped.

Answer

nayem picture nayem · Mar 20, 2017

I assume your url is an URL type. If so try this out:

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
}

Saying enough, you should change your implementation like this:

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
}

EDIT: 1

There is even more better way, you can call it swift-way (:D). You don't have to explicitly check for file existence.

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)

Update for Swift 3.0+ without the Objective-Cish NS prefix:

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