Can't save a file in a Documents directory in macOS - swift

I created a function to save a data.txt file in ~/Documents directory.
But it doesn't save a file at all.
func SaveFile(){
print("save file")
let file_name = "data.txt"
let text = "12345"
let fm = FileManager.default
do {
let docsurl = try! fm.url(for: .documentDirectory, in: .userDomainMask, appropriateFor:nil, create:false)
let fileURL = docsurl.appendingPathComponent(file_name)
try text.write( to: fileURL, atomically: false, encoding: String.Encoding.utf8 )
} catch {
print("error: \(error)")
}
}
In the output area there is only text save file.
What am I doing wrong?

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.")
}
}

FileManager.default.fileExists(atPath:) showing nil after saving string to filepath

When I create a filePath for an image then write it to the filePath, it doesn't load the image in the loadImageViewController
saveImageViewController:
let fileManager = FileManager.default
let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
let documentPath = documentsURL.path
let filePath = documentsURL.appendingPathComponent("profile_image.png")
do {
let files = try fileManager.contentsOfDirectory(atPath: documentPath)
for file in files {
if "\(documentPath)/\(file)" == filePath.path {
try fileManager.removeItem(atPath: filePath.path)
}
}
} catch {
print("Could not add image from document directory: \(error)")
}
do {
if let pngImageData = profilePicImageView.image!.pngData() {
try pngImageData.write(to: filePath, options: .atomic)
}
} catch {
print("couldn't write image")
}
entity.profilePicPath = filePath.path
loadImageViewController:
if FileManager.default.fileExists(atPath: entity.profilePicPath!) {
let contentsOfFilePath = UIImage(contentsOfFile: entity.profilePicPath!)
cell.entityImage.image = contentsOfFilePath
}
I am saving the file path as a string through core data.

How to encode data on a JSON file in swift

In my swift app I'm trying to encode data on a local txt file, this is my code:
func encodeData(data: String) {
let file = "myfile.txt"
if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let fileURL = dir.appendingPathComponent(file)
do {
try data.write(to: fileURL, atomically: false, encoding: .utf8)
print(fileURL)
}
catch {print(error.localizedDescription)}
}
}
This is the path:
/var/mobile/Containers/Data/Application/A9C39138-27D4-4D6A-8D92-118315E01A9C/Documents/myfile.txt
But how can I find my txt file named myfile.txt ?

How To Get This To Save To Where My App Is Located

Save data to file
let fileName = "Test"
let DocumentDirURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let fileURL = DocumentDirURL.appendingPathComponent(fileName).appendingPathExtension("txt")
print("FilePath: \(fileURL.path)")
let writeString = "Write this text to the fileURL as text in iOS using Swift"
do {
// Write to the file
try writeString.write(to: fileURL, atomically: true, encoding: String.Encoding.utf8)
} catch let error as NSError {
print("Failed writing to URL: \(fileURL), Error: " + error.localizedDescription)
}
var readString = "" // Used to store the file contents
do {
// Read the file contents
readString = try String(contentsOf: fileURL)
} catch let error as NSError {
print("Failed reading from URL: \(fileURL), Error: " + error.localizedDescription)
}
print("File Text: \(readString)")
How can I get this to save the Test.txt file to save where my App directory is. I don't know where this is saving the Text File to.

Trying to clear document folder Swift

I use following method to add file (download) to document directory:
static func downloadFileWithLink(linkString : String){
// Create destination URL
let documentsUrl:URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
let destinationFileUrl = documentsUrl.appendingPathComponent("downloadedFile")
//Create URL to the source file you want to download
let fileURL = URL(string: linkString)
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig)
let request = URLRequest(url:fileURL!)
let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
if let tempLocalUrl = tempLocalUrl, error == nil {
// Success
if let statusCode = (response as? HTTPURLResponse)?.statusCode {
print("Successfully downloaded. Status code: \(statusCode)")
}
do {
try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
} catch (let writeError) {
print("Error creating a file \(destinationFileUrl) : \(writeError)")
}
} else {
print("Error took place while downloading a file. Error description: %#", error?.localizedDescription);
}
}
task.resume()
}
It simply download file to document folder in sandbox. I looked for method that delete files in documents folder, and tried following:
static func deleteFiledInDocDirectory(){
let fileManager = FileManager.default
let tempFolderPath = NSTemporaryDirectory()
do {
let filePaths = try fileManager.contentsOfDirectory(atPath: tempFolderPath)
for filePath in filePaths {
try fileManager.removeItem(atPath: tempFolderPath + filePath)
}
} catch {
print("Could not clear temp folder: \(error)")
}
}
However, when i inspect sandbox, downloaded file is still here. How to delete it?
In deleteFiledInDocDirectory() you're using NSTemporaryDirectory instead of the documents directory that you originally saved the file to.
Change tempFolderPath to be set using following:
guard let tempFolderPath = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first else {
return // documents directory not found for some reason
}
The full method:
static func deleteFiledInDocDirectory(){
guard let tempFolderPath = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first?.absoluteString else {
return // documents directory not found for some reason
}
let fileManager = FileManager.default
do {
let filePaths = try fileManager.contentsOfDirectory(atPath: tempFolderPath)
for filePath in filePaths {
try fileManager.removeItem(atPath: tempFolderPath + filePath)
}
} catch {
print("Could not clear temp folder: \(error)")
}
}