从文档目录中删除文件

Deleting files from Documents Directory

我将图像保存在文档目录中,并允许用户编辑图像,因此如果用户想要更改图像,我将删除以前的图像,然后保存新图像。在同一条路上。

有我的删除功能:

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

当我试图覆盖图像时有功能:

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
    }

当我更改图像时,print("Confirmed") 在控制台上。

而且我认为它工作正常,因为用户可以看到新图像并且该图像是为用户显示的。但是当我转到 iPhone 数据设置时,我可以看到每当我更改图像时,我的应用程序数据都在增长。现在我有 100mb 的数据。

为什么不能正常工作?

首先你可以使用下面的函数查看目录的大小,看看那里发生了什么

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
}

同时在文档目录中创建临时文件夹

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!

    }

从临时目录中删除文件:

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

问题已解决!

我的功能运行良好。我发现每张挑选的照片(来自 UIPicker)都保存在我应用程序的 tmp 文件夹中。

解决此问题的方法是清理 tmp 文件夹: [How to remove tmp directory files of an ios app?