Reputation: 15
See Image as referenceI am working on a project, in which i need to show a UICollectionview, which includes files from filemanager, in this collectionview i am displaying images as well as folders. And there is also a button which deletes the selected cells. So how can i delete selected folder/images from document directory?
I am creating folder with this function.
func createDir() {
let manager = FileManager.default
guard let url = manager.urls(for: .documentDirectory, in: .userDomainMask).first else {
return
}
print("url path is ==>>",url.path)
let folderName = url.appendingPathComponent(folderNameTextField.text!)
do {
try manager.createDirectory(at: folderName, withIntermediateDirectories: true, attributes: [:])
print("Saved")
listFilesFromDocumentsFolder()
// getAllDirectoriesList()
}
catch {
print(error)
}
}
`And saving images with this function
func saveImageToDocumentDirectory(image: UIImage ) {
let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
//
let fileName = "Doc-" + dateFormatter.string(from: Date())
let fileURL = documentsDirectory.appendingPathComponent(fileName
)
if let data = image.jpegData(compressionQuality: 1.0),!FileManager.default.fileExists(atPath: fileURL.path){
do {
try data.write(to: fileURL)
print("file saved")
} catch {
print("error saving file:", error)
}
}
}
I am using this function to delete, it works but abnormally,
for file in folderImageArray {
try! FileManager.default.removeItem(at: file)
}
And This function making a crash.
for file in folderNameArray {
try! FileManager.default.removeItem(atPath: file)
}
Upvotes: 1
Views: 1065
Reputation: 894
You should not force unwrap try block, Use do try at-least it will give you the reason why it's not working. Also adding a little delay will work fine
for file in folderImageArray {
do {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
try FileManager.default.removeItem(at: file)
}
} catch {
print("File Deletion Failed: \(error.localizedDescription)")
}
}
Upvotes: 1