How to Check If a File Exists in the Documents Directory in Swift

How to check if a file exists in the Documents directory in Swift?

Swift 4.x version

    let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let url = NSURL(fileURLWithPath: path)
if let pathComponent = url.appendingPathComponent("nameOfFileHere") {
let filePath = pathComponent.path
let fileManager = FileManager.default
if fileManager.fileExists(atPath: filePath) {
print("FILE AVAILABLE")
} else {
print("FILE NOT AVAILABLE")
}
} else {
print("FILE PATH NOT AVAILABLE")
}

Swift 3.x version

    let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let url = URL(fileURLWithPath: path)

let filePath = url.appendingPathComponent("nameOfFileHere").path
let fileManager = FileManager.default
if fileManager.fileExists(atPath: filePath) {
print("FILE AVAILABLE")
} else {
print("FILE NOT AVAILABLE")
}

Swift 2.x version, need to use URLByAppendingPathComponent

    let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
let url = NSURL(fileURLWithPath: path)
let filePath = url.URLByAppendingPathComponent("nameOfFileHere").path!
let fileManager = NSFileManager.defaultManager()
if fileManager.fileExistsAtPath(filePath) {
print("FILE AVAILABLE")
} else {
print("FILE NOT AVAILABLE")
}

How to check if multiple files exist in documents directory? (Swift)

Write a method for example

func checkFiles(with fileNames: [String] {
for fileName in fileNames {
let fileURL = documentsDirectoryURL.appendingPathComponent(fileName)
if !FileManager.default.fileExists(atPath: fileURL.path) {
removeImage(itemName: fileName, fileExtension: "jpg")
} else {
print("There was no image to remove at", fileURL)
}
}
}

and call it

let fileNames = ["savedpicture1", "savedpicture2", "savedpicture3",  "savedpicture4"] 
checkFiles(with: fileNames)

How would I check for a file in a specified directory in Swift 5?

Figured it out. Here's what I put for Swift 5.

let path = NSString(string: "~/test-node.js").expandingTildeInPath
let fileDoesExist = FileManager.default.fileExists(atPath: path)

The "~/test-node.js" should be replaced with the path of the file you want to verify exists.

How to check if a file exists in Documents folder?


Swift 3:

let documentsURL = try! FileManager().url(for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true)

... gives you a file URL of the documents directory. The following checks if there's a file named foo.html:

let fooURL = documentsURL.appendingPathComponent("foo.html")
let fileExists = FileManager().fileExists(atPath: fooURL.path)

Objective-C:

NSString* documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];

NSString* foofile = [documentsPath stringByAppendingPathComponent:@"foo.html"];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:foofile];

How check directory exist?

You can do smarter solution Like that without Two function completion(isExit,directoryURL) :

And simple use it in one line :

 self.createSystemFolders("json") { (isExit, url) in
print(isExit)
print(url)
}

CreateSystemFolders:

 func createSystemFolders(_ folderName:String ,_ completion:(_ isExit:Bool?,_ directoryURL:URL?) -> Void){
let paths = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true)
let directory = paths[0]
let fileManager = FileManager.default

let url = URL(fileURLWithPath: directory).appendingPathComponent(folderName)


if !fileManager.fileExists(atPath: url.path) {
do {
try fileManager.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil)
completion(false,url)
}
catch {
print("Error: Unable to create directory: \(error)")
completion(nil,nil)
}
var url = URL(fileURLWithPath: directory)
var values = URLResourceValues()
values.isExcludedFromBackup = true
do {
try url.setResourceValues(values)
completion(false,url)
}
catch {
print("Error: Unable to exclude directory from backup: \(error)")
completion(nil,nil)
}
}else{
completion(true,url)
}
}

FileManager.default.fileExists says documents directory does not exist

Turns out one should use documentsURL.path, instead of any sort of URL.

The path begins with /var/mobile... whereas the URLs begin with file:///var...

Check if file exists at URL instead of path


if (![fileManager fileExistsAtPath:[storeURL path]]) 
...

From the documentation:

If this URL object contains a file URL (as determined with isFileURL),
the return value of this method is suitable for input into methods of
NSFileManager or NSPathUtilities. If the path has a trailing slash it
is stripped.



Related Topics



Leave a reply



Submit