从文档目录中删除文件

时间:2019-12-29 15:19:33

标签: swift directory document delete-operator

我将图像保存在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数据设置时,只要更改图像,我就可以看到,我的App数据正在增长。现在我有100mb的数据。

为什么它不能正常工作?

2 个答案:

答案 0 :(得分:2)

首先,您可以使用以下功能查看目录的大小,以查看目录中发生的事情

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

答案 1 :(得分:0)

问题解决了!

我的功能运行正常。我发现,每张从UIPicker拾取的照片都保存在应用程序的tmp文件夹中。

一个解决方案是清理tmp文件夹: [How to remove tmp directory files of an ios app?