简体   繁体   中英

Deleting files from Documents Directory

I'm saving Images in Documents Directory and I allow user to edit Images, so if user want to change Image, I'm deleting previous image and then I'm saving new one. At the same path.

There is my deleting function:

func deleteItemInDirectory(imageName: String) {
    let fileManager = FileManager.default
    let imagePath = (self.getDirectoryPath() as NSString).appendingPathComponent(imageName)
    do {
        if fileManager.fileExists(atPath: imagePath) {
            try fileManager.removeItem(atPath: imagePath)
            print("Confirmed")
        }
        else {
            print("nothing happened")
        }
    }
    catch let error as NSError {
        print("An error took place: \(error)")
    }
}

And there is function when I'm trying to overwrite image:

func saveItem() {
    if self.nick != ""{
        self.ShowingEmptyFieldsAlert = false
        let imageName = self.user.imageName!

        self.user.name = self.nick
        self.user.birthday = self.birthday
        if self.pickedImage != nil {
            ImageToDirectory().deleteItemInDirectory(imageName: imageName)
            ImageToDirectory().saveImageToDocumentDirectory(image: self.pickedImage!, filename: imageName)
        }

        try? self.moc.save()
        self.presentationMode.wrappedValue.dismiss()
    }
    else {
        self.ShowingEmptyFieldsAlert = true
    }

When I'm changing image, print("Confirmed") is on Console.

And I've thought it works fine, because User can see new image and this image is shown for user. But When I go to iPhone Data settings, I can see whenever I change image, my App Data is growing. Now I have 100mb of data.

Why It doesn't work properly?

At first you can see the size of the directory using below function to see what is happening there

func directorySize(url: URL) -> Int64 {
    let contents: [URL]
    do {
        contents = try FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys: [.fileSizeKey, .isDirectoryKey])
    } catch {
        return 0
    }

    var size: Int64 = 0

    for url in contents {
        let isDirectoryResourceValue: URLResourceValues
        do {
            isDirectoryResourceValue = try url.resourceValues(forKeys: [.isDirectoryKey])
        } catch {
            continue
        }

        if isDirectoryResourceValue.isDirectory == true {
            size += directorySize(url: url)
        } else {
            let fileSizeResourceValue: URLResourceValues
            do {
                fileSizeResourceValue = try url.resourceValues(forKeys: [.fileSizeKey])
            } catch {
                continue
            }

            size += Int64(fileSizeResourceValue.fileSize ?? 0)
        }
    }
    return size
}

Also Create Temp Folder in Document Directory

func getDocumentsDirectory() -> URL {
        //        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        //        return paths[0]

        let fileManager = FileManager.default
        if let tDocumentDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first {
            let filePath =  tDocumentDirectory.appendingPathComponent("MY_TEMP")
            if !fileManager.fileExists(atPath: filePath.path) {
                do {
                    try fileManager.createDirectory(atPath: filePath.path, withIntermediateDirectories: true, attributes: nil)
                } catch {
                    NSLog("Couldn't create folder in document directory")
                    NSLog("==> Document directory is: \(filePath)")
                    return fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
                }
            }

            NSLog("==> Document directory is: \(filePath)")
            return filePath
        }
        return fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!

    }

Remove Files From Temp Directory:

func clearAllFilesFromTempDirectory(){        
        let fileManager = FileManager.default
        do {
            let strTempPath = getDocumentsDirectory().path
            let filePaths = try fileManager.contentsOfDirectory(atPath: strTempPath)
            for filePath in filePaths {
                try fileManager.removeItem(atPath: strTempPath + "/" + filePath)
            }
        } catch {
            print("Could not clear temp folder: \(error)")
        }
    }

Problem solved!

My functions are working fine. I found that every picked photo (from UIPicker) is saved in tmp folder in my app.

A solution to this is cleaning tmp folder: [ How to remove tmp directory files of an ios app?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM