简体   繁体   English

从文档目录中删除文件

[英]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.当我更改图像时, print("Confirmed")在控制台上。

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.但是当我进入 iPhone 数据设置时,我可以看到每当我更改图像时,我的应用程序数据都在增长。 Now I have 100mb of data.现在我有 100mb 的数据。

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.我发现每张选择的照片(来自 UIPicker)都保存在我的应用程序的 tmp 文件夹中。

A solution to this is cleaning tmp folder: [ How to remove tmp directory files of an ios app?对此的解决方案是清理 tmp 文件夹:[ 如何删除 ios 应用程序的 tmp 目录文件?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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