How create folder in documents app in iPhone folder - swift

How can im create folder in documents app.
Im tried this:
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory: String = paths.first ?? ""
let dataPath = documentsDirectory + "/yourFolderName"
if !FileManager.default.fileExists(atPath: dataPath) {
try? FileManager.default.createDirectory(atPath: dataPath, withIntermediateDirectories: false, attributes: nil)
}
Example:
Folder inside iPhone folder:

Related

Unable to save multiple text files in same folder (MacOS Swift Application)

I am trying to save multiple text files in the same folder. So far I can save one text file into a generated folder in my document directory, but I cannot save more than one text file in that same folder.
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory = paths[0]
let docURL = URL(string: documentsDirectory)!
let dataPath = docURL.appendingPathComponent("User_Notes")
// this is the folder name
if !FileManager.default.fileExists(atPath: dataPath.path) {
do {
try
FileManager.default.createDirectory(atPath: dataPath.path, withIntermediateDirectories: true, attributes: nil)
// try stringToWrite.write(to: &dataPath)
try stringToWrite.write(toFile: "\(dataPath)/\(userNotes)).txt", atomically: true, encoding: String.Encoding.utf8)
} catch {
print(error.localizedDescription)
}
}
if error != nil {
print("Error saving user data.")
}
}

Downloading tflite models from server rather than using the models from assets folder in Swift

I have seen tensorflow lite examples for iOS and they resides in the assets folder.
We have some model on the server that I want to download and keep on document directory and use.
Here is how I download and save the model to the document directory.
class ModelFileManager {
let folderRoute = "Models"
func saveModel(with file: String, data: Data, extension fileExtension: String) {
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent(folderRoute, isDirectory: true)
if !FileManager.default.fileExists(atPath: documentsDirectory.path) {
do {
try FileManager.default.createDirectory(atPath: documentsDirectory.path, withIntermediateDirectories: true, attributes: nil)
} catch {
print(error)
}
}
let fileURL = documentsDirectory.appendingPathComponent("\(file).\(fileExtension)", isDirectory: false)
do {
try data.write(to: fileURL)
print("File save at \(fileURL.absoluteString)")
} catch {
print("File can't not be save at path \(fileURL.absoluteString), with error : \(error)");
}
}
func fetchModel(for name: String) -> String {
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent(folderRoute, isDirectory: true)
let fileURL = documentsDirectory.appendingPathComponent("\(name)", isDirectory: false)
return fileURL.absoluteString
}
}
So when I give the path of the file to the Interpreter, it says
The model is not a valid Flatbuffer file
Failed to create the interpreter with error: Failed to load the given model.
I solved this by replacing the file:/// with empty string from absoluteString
func fetchModel(for name: String) -> String {
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent(folderRoute, isDirectory: true)
let fileURL = documentsDirectory.appendingPathComponent("\(name)", isDirectory: false)
return fileURL.absoluteString.replacingOccurrences(of: "file:///", with: "")
}

create plist and copy it to folder MacOS Swift

I have been racking my brain on how to create and write a plist to a certain Folder Directory in MacOS. In my case to the LaunchDaemons folder in /Library. I know how to create the plist but its the writing to the LaunchDaemons folder that I am having issues with. This code below from my understanding is for the sandbox but how do I do it outside of the sandbox? Cheers
let fileManager = FileManager.default
let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let path = documentDirectory.appending("test.plist")
I have added the code with the help I have received and have no errors but it is not writing anything to the folder. Here is the code:
let libraryDirectory = try! FileManager.default.url(for: .libraryDirectory, in: .localDomainMask, appropriateFor: nil, create: false)
let launchDaemonsFolder = libraryDirectory.appendingPathComponent("LaunchDaemons/test.plist")
if FileManager.default.fileExists(atPath: launchDaemonsFolder.path) {
print(launchDaemonsFolder)
let plistDictionary : [String: Any] = [
"ExitTimeOut": 600,
"Label": "BOOT.SHUTDOWN.SERVICE",
"ProgramArguments": ["/test.sh"] as Array,
"RunAtLoad": false,
"WorkingDirectory": "/"
]
let dictionaryResult = NSDictionary(dictionary: plistDictionary)
let fileWritten = dictionaryResult.write(to: launchDaemonsFolder, atomically: true)
print("is the file created: \(fileWritten)")
} else {
print("File Exists")
}
First of all NSSearchPathForDirectoriesInDomains is outdated, it's highly recommended to use the URL related API anyway.
This code creates an URL pointing to /Library/LaunchDaemons
let libraryDirectory = try! FileManager.default.url(for: .libraryDirectory, in: .localDomainMask, appropriateFor: nil, create: false)
let launchDaemonsFolder = libraryDirectory.appendingPathComponent("LaunchDaemons")

How can I find the path of iOS app internal directory in Swift?

How can I find the path of iOS app internal directory in Swift?
Firstly, what is the equivalent name of android app internal directory in iOS app?
Secondly, how can I find the path of the directory?
which api should I use in Swift?
My main purpose is trying to copy Bundle sqlite file to the directory
To get path of document directory you can use this code.
// path to documents directory
let documentDirectoryPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
if let documentDirectoryPath = documentDirectoryPath {
}
For more information follow these links : File System Basics and Accessing Files and Directories
Try this -
public func getDatabasePath() -> String {
let databaseURL = try? FileManager.default
.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("YOUR_DB_FILE_NAME.sqlite")
// If DB file not present in file manager copy DB file to user document directory
let fileManager = FileManager.default
if fileManager.fileExists(atPath: (databaseURL?.path)!) {
print("FILE AVAILABLE")
return (databaseURL?.path)!
} else {
print("FILE NOT AVAILABLE ... Copying")
if fileManager.createFile(atPath: (databaseURL?.path)!, contents: Data(), attributes: nil) {
return (databaseURL?.path)!
}
}
return ""
}

iOS9 Swift File Creating NSFileManager.createDirectoryAtPath with NSURL

Before iOS9, we had created a directory like so
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String
let logsPath = documentsPath.stringByAppendingPathComponent("logs")
let errorPointer = NSErrorPointer()
NSFileManager.defaultManager().createDirectoryAtPath(logsPath, withIntermediateDirectories: true, attributes: nil, error: errorPointer)
But with iOS9 they removed String.stringByAppendingPathComponent. The auto convert tool replaced our use of String with NSURL. createDirectoryAtPath() takes a string so I need to convert the NSURL to a string. We used absolutePath like so: (update for iOS9)
let documentsPath = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0])
let logsPath = documentsPath.URLByAppendingPathComponent("logs")
do {
try NSFileManager.defaultManager().createDirectoryAtPath(logsPath.absoluteString, withIntermediateDirectories: true, attributes: nil)
} catch let error as NSError {
NSLog("Unable to create directory \(error.debugDescription)")
}
But I am getting the following error:
Unable to create directory Error Domain=NSCocoaErrorDomain Code=513
"You don’t have permission to save the file “logs” in the folder
“Documents”."
UserInfo={NSFilePath=file:///var/mobile/Containers/Data/Application/F2EF2D4F-94AF-4BF2-AF9E-D0ECBC8637E7/Documents/logs/,
NSUnderlyingError=0x15664d070 {Error Domain=NSPOSIXErrorDomain Code=1
"Operation not permitted"}}
I figured this one out. createDirectoryAtPath() is unable to process a path with the "file://" prefix. To get a path without the prefix you must use path() or relativePath().
let documentsPath = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0])
let logsPath = documentsPath.URLByAppendingPathComponent("logs")
do {
try NSFileManager.defaultManager().createDirectoryAtPath(logsPath.path!, withIntermediateDirectories: true, attributes: nil)
} catch let error as NSError {
NSLog("Unable to create directory \(error.debugDescription)")
}
Incorrect path (notice file://):
file:///var/mobile/Containers/Data/Application/F2EF2D4F-94AF-4BF2-AF9E-D0ECBC8637E7/Documents/logs/
Correct path:
/var/mobile/Containers/Data/Application/F2EF2D4F-94AF-4BF2-AF9E-D0ECBC8637E7/Documents/logs/
Swift 3
let documentsPath = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0])
let logsPath = documentsPath.appendingPathComponent("logs")
do {
try FileManager.default.createDirectory(at: logsPath!, withIntermediateDirectories: true, attributes: nil)
} catch let error as NSError {
NSLog("Unable to create directory \(error.debugDescription)")
}
Swift 4
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let logsPath = paths[0].appendingPathComponent("logs")
do {
try FileManager.default.createDirectory(at: logsPath, withIntermediateDirectories: true, attributes: nil)
} catch let error as NSError {
NSLog("Unable to create directory \(error.debugDescription)")
}