Search code examples
swiftnsfilemanager

fileExistsAtPath check for filename?


How to check whether there is a file in a directory with only the name without extension? Now the files are written in my directory, their name will be generated from the id file. Accordingly, when I'm looking for a file, let file = "\ (fileId) .pdf", in the directory it is, but if no extension, it will not be found. Either return as easier extension from the server?

public var  isDownloaded: Bool {
    let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
    let url = NSURL(fileURLWithPath: path)
    let filePath = url.URLByAppendingPathComponent("\(fileMessageModel.attachment.id)")!.path!
    let fileManager = NSFileManager.defaultManager()
    return fileManager.fileExistsAtPath(filePath)
}

Solution

  • enumeratorAtPath creates a deep enumerator -- i.e. it will scan contents of subfolders and their subfolders too. For a shallow search, user contentOfDirectortAtPath:

    func file(fileName: String, existsAt path: String) -> Bool {
        var isFound = false
    
        if let pathContents = try? NSFileManager.defaultManager().contentsOfDirectoryAtPath(path) {
            pathContents.forEach { file in
                if (file as NSString).stringByDeletingPathExtension == fileName {
                    isFound = true
                    return
                }
            }
        }
        return isFound
    }
    
    if let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first {
        if file("something", existsAt: path) {
            // The file exists, do something about it
        }
    }