func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
}
So simply, I get my filename using that function.And it returns correctly for now, how can I delete this file using Swift 3?
And How can I read the image back like UIImageJPEGRepresentation
?
let image_data = UIImageJPEGRepresentation(self.commons.correctlyOrientedImage(image: self.imageSelected.image!),0.5)
I did following and its not working
let filename = getDocumentsDirectory().appendingPathComponent("l.png") let
fileManager = FileManager.default var filePath = filename // Check if file exists
if fileManager.fileExists(atPath: filePath.absoluteString) { // Delete file try fileManager.removeItem(atPath: filePath.absoluteString) } else { print("File does not exist") }
I save the file like this
let filename = getDocumentsDirectory().appendingPathComponent("COPY111.PNG") try? image_data?.write(to: filename)
But I cannot remove it from answers provided below
Delete Files in PowerShell using Remove-Item cmdlet In PowerShell, the Remove-Item cmdlet deletes one or more items from the list. It utilizes the path of a file for the deletion process. Using the “Remove-Item” command, you can delete files, folders, variables, aliases, registry keys, etc.
There're lines for deleting a file:
do {
try FileManager.default.removeItem(at: fileName)
} catch let error as NSError {
print("Error: \(error.domain)")
}
And here's code for setting it to imageView:
if let image = UIImage(contentsOfFile: fileName) {
imageView.image = image
}
Try this. Hope it will work.To delete a file
let fileNameToDelete = "myFileName.txt"
var filePath = ""
// Fine documents directory on device
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentDirectory = paths[0]
filePath = documentDirectory.appendingFormat("/" + fileNameToDelete)
do {
let fileManager = FileManager.default
// Check if file exists
if fileManager.fileExists(atPath: filePath) {
// Delete file
try fileManager.removeItem(atPath: filePath)
} else {
print("File does not exist")
}
}
catch let error as NSError {
print("An error took place: \(error)")
}
Source : http://swiftdeveloperblog.com/code-examples/delete-file-example-in-swift/
For image loading:
let imageData = UIImageJPEGRepresentation(image)!
let docDir = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let imageURL = docDir.appendingPathComponent("tmp.jpeg")
try! imageData.write(to: imageURL)
let newImage = UIImage(contentsOfFile: imageURL.path)!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With