Read all files from a directory? - swift

I am trying to create a folder in my assets, then get a list of files inside.
Sounds simple but there is no clean answer on how to do exactly this.
Even to get the list from the main directory, most people can't do on Swift 3, reading here : Getting list of files in documents folder
using :
let fileMngr = FileManager.default;
// Full path to documents directory
let docs = fileMngr.urls(for: .documentDirectory, in: .userDomainMask)[0].path
// List all contents of directory and return as [String] OR nil if failed
return try? fileMngr.contentsOfDirectory(atPath:docs)
Not working.
Reading from a specific folder, I couldn't understand how to get it's path for swift.
Any example that really work that reads from a folder ?

If you want to get all files in a personal directory, here is the simple answer
do {
let documentURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let Path = documentURL.appendingPathComponent("yourDirectoyName").absoluteURL
let directoryContents = try FileManager.default.contentsOfDirectory(at: Path, includingPropertiesForKeys: nil, options: [])
}
catch {
print(error.localizedDescription)
}
And then if you want for example to read all files with special extension, you can do it that way
static func listAllFileNamesExtension(nameDirectory: String, extensionWanted: String) -> (names : [String], paths : [URL]) {
let documentURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let Path = documentURL.appendingPathComponent(nameDirectory).absoluteURL
do {
try FileManager.default.createDirectory(atPath: Path.relativePath, withIntermediateDirectories: true)
// Get the directory contents urls (including subfolders urls)
let directoryContents = try FileManager.default.contentsOfDirectory(at: Path, includingPropertiesForKeys: nil, options: [])
// if you want to filter the directory contents you can do like this:
let FilesPath = directoryContents.filter{ $0.pathExtension == extensionWanted }
let FileNames = FilesPath.map{ $0.deletingPathExtension().lastPathComponent }
return (names : FileNames, paths : FilesPath);
} catch {
print(error.localizedDescription)
}
return (names : [], paths : [])
}
So if you want to have all your json files in your personal directory
let allJsonNamePath = listAllFileNamesExtension(nameDirectory:"yourDirectoryName", extensionWanted: "json")

Swift 4/5
let documentDirectoryPath:String = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let myFilesPath = "\(documentDirectoryPath)/myfolder"
let filemanager = FileManager.default
let files = filemanager.enumerator(atPath: myFilesPath)
while let file = files?.nextObject() {
print(file)
}

Actually, amazingly, for 2 days no one could tell me the real issue here.
Creating a group, is completely different from dragging a folder into the project.
For some reason, with Apple, its always complicated with files. I have to figure out the NOT so intuitive approach that a group that looks like a folder, is nothing but a nice way to look at something, and will not create a real folder accessible by the file manager.
This strange approach is maybe intutitive to a very pro programmer, but really not to any simple person.
Simply put, create a blue folder outside Xcode and drag it in.

Related

Can't find the json file that I created

I used this code for encoding some data into a json file, but I can't really find the location of the file.
func save () {
let users: [UserCredentials] = []
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
do {
let data = try encoder.encode(users)
let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("users.json")
try data.write(to: url)
} catch {
print("Error encoding JSON: \(error)")
}
}
I didn't find anything in the Document directory. Then I found out that I have to go to my Bundle ID that's located in library/application support, but I didn't find mine there.
Any idea where that json file is hiding?
Insert the line print(url.path) after the let url... line.
Run the code.
Copy (⌘C) the printed path in the console.
Switch to Finder, press ⇧⌘G, then ⌘V and return.

NSKeyedArchiver.archiveRootObject fails to save

I have a group of custom objects that I'm converting to NSMutableDictionary's, and then creating an array out of them (this part is currently working as expected).
I'm then attempting to save that array of data as a file using NSKeyedArchiver. However, the result of NSKeyedArchiver.archiveRootObject always returns false.
Below is my logic for saving - am I missing something obvious, or perhaps is this the wrong approach? Thank you!
var groupsArray = [Any?]()
for group in file!.groups{
for obj in group.children {
let objDict = obj.convertToDictionary()
groupsArray.append(objDict)
}
}
let documents: String = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let filePath: String = URL(fileURLWithPath: documents).appendingPathComponent("file.archive").absoluteString
let save: Bool = NSKeyedArchiver.archiveRootObject(groupsArray, toFile: filePath)
EDIT: This also fails if trying to save to the .desktop or the .caches directories.
The issue here is .absoultestring. If the URL object contains a file URL, then we should use .path for working with FileManager or PathUtilities etc. So here replacing .absoultestring with .path will solve the issue
for more details about their difference please refer this answer
try this method to save
1.Method returns filepath.
func filePath(key:String) -> String {
let manager = FileManager.default
let url = manager.urls(for: .documentDirectory, in: .userDomainMask).first
return (url!.appendingPathComponent(key).path)
}
2.Code to save to a file using NSKeyedArchiver.
NSKeyedArchiver.archiveRootObject(groupsArray, toFile: filePath(key: "file.archive"))

Creating Folder in Application Support if not Exists

I'm trying to create a folder in Application Support Directory.
let path = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
let fileurl = path.appendingPathComponent("my folder")
do {
try FileManager.default.createDirectory(atPath:String(describing: fileurl), withIntermediateDirectories: true, attributes: nil)
} catch {
print(error)
}
But no folder is created.What I'm I doing wrong?
The error occurs because you are passing the string representation of an URL which includes the file:// scheme but createDirectory(atPath expects a path without the file:// scheme.
The solution is so easy: (Always) use the URL related API of FileManager
try FileManager.default.createDirectory(at: fileurl, withIntermediateDirectories: true)
Please consider a more meaningful variable naming
path is actually url
fileurl is actually folderurl

FileManager.contentsEqual returns false when comparing copied files

I need to preload SQLite files from my bundle's resources into the application support directory. I want to make sure the correct files are there vs. the empty files that Core Data puts there by default. To do this, I'm using FileManager.default.contentsEqual; however, this always returns false.
I tried testing with a playground, but the copy there is creating alias files, still resulting in a false comparison.
In the app, the files do copy over with the same name and size. The dates are different: the copies have the current date/time rather than the original's timestamps. Using contentsEqual, though, I wouldn't think that matters.
Update: diff at the command line shows the files are the same...
What am I missing?
Here's the code from the playground, which is virtually the same as my app code:
// get the URL for the application support directory
let appSupportDir: URL = try!
FileManager.default.url(for: FileManager.SearchPathDirectory.applicationSupportDirectory,
in: FileManager.SearchPathDomainMask.userDomainMask,
appropriateFor: nil, create: true)
// get the source URLs for the preload files
let sqliteFileBundleURL: URL = Bundle.main.url(forResource: "My_DB", withExtension: "sqlite")!
let sqliteShmFileBundleURL: URL = Bundle.main.url(forResource: "My_DB", withExtension: "sqlite-shm")!
let sqliteWalFileBundleURL: URL = Bundle.main.url(forResource: "My_DB", withExtension: "sqlite-wal")!
// create target URLs for copy to application support directory
let sqliteFileAppSptURL: URL = appSupportDir.appendingPathComponent("My_DB.sqlite")
let sqliteShmFileAppSptURL: URL = appSupportDir.appendingPathComponent("My_DB.sqlite-shm")
let sqliteWalFileAppSptURL: URL = appSupportDir.appendingPathComponent("My_DB.sqlite-wal")
// remove the files if they already exist at the target (for test - app doesn't do this)
do {
let filesFound: [URL] = try FileManager.default.contentsOfDirectory(at: appSupportDir,
includingPropertiesForKeys: nil,
options: .skipsHiddenFiles)
if !filesFound.isEmpty {
for fileURL in filesFound {
try FileManager.default.removeItem(at: fileURL)
}
print("Removed \(filesFound.count) files without error.")
}
}
catch {
print("Error:\n\(error)")
}
// copy the files to the application support directory
do {
try FileManager.default.copyItem(at: sqliteFileBundleURL, to: sqliteFileAppSptURL)
try FileManager.default.copyItem(at: sqliteShmFileBundleURL, to: sqliteShmFileAppSptURL)
try FileManager.default.copyItem(at: sqliteWalFileBundleURL, to: sqliteWalFileAppSptURL)
}
catch {
print("Error: \(error)")
}
// compare the copied target files to their source using contentsEqual
let sqliteFileCopied: Bool =
FileManager.default.contentsEqual(atPath: sqliteFileBundleURL.absoluteString, andPath: sqliteFileAppSptURL.absoluteString)
let sqliteShmFileCopied: Bool =
FileManager.default.contentsEqual(atPath: sqliteShmFileBundleURL.absoluteString, andPath: sqliteShmFileAppSptURL.absoluteString)
let sqliteWalFileCopied: Bool =
FileManager.default.contentsEqual(atPath: sqliteWalFileBundleURL.absoluteString, andPath: sqliteWalFileAppSptURL.absoluteString)
Aha! When using FileManager, one should be using path rather than absoluteString to convert a URL to a String:
// compare the copied target files to their source using contentsEqual
let sqliteFileCopied: Bool =
FileManager.default.contentsEqual(atPath: sqliteFileBundleURL.path, andPath: sqliteFileAppSptURL.path)
let sqliteShmFileCopied: Bool =
FileManager.default.contentsEqual(atPath: sqliteShmFileBundleURL.path, andPath: sqliteShmFileAppSptURL.path)
let sqliteWalFileCopied: Bool =
FileManager.default.contentsEqual(atPath: sqliteWalFileBundleURL.path, andPath: sqliteWalFileAppSptURL.path)
The difference between the two is that path generates a file system-type path:
/var/folders/kb/y2d_vrl133d1b04_5kc3kw880000gn/T/com.apple.dt.Xcode.pg/resources/238FF955-236A-42FC-B6EA-9A74FC52F235/My_DB.sqlite
whereas absoluteString generates a browser-friendly path:
file:///var/folders/kb/y2d_vrl133d1b04_5kc3kw880000gn/T/com.apple.dt.Xcode.pg/resources/238FF955-236A-42FC-B6EA-9A74FC52F235/My_DB.sqlite
Note: path also works in the playground with the alias files.

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)
}
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
}
}
What about iterating over the files in the directory and testing the name with extension excluded?
let filemanager:FileManager = FileManager()
let files = filemanager.enumeratorAtPath(/* your directory path */)
while let file = files?.nextObject() {
// Remove file name extension
// Do file name comparison here
}
In terms of time complexity is will be O(n), however, as long as there are not too many files, you are good to go. On the other hand, if there are many files, you will need to consider a more efficient way to traverse, may be a trie data structure consisted of all file names in that directory.