在iOS中使用Swift删除文件

0md85ypi  于 2023-05-19  发布在  iOS
关注(0)|答案(3)|浏览(165)

考虑:

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

所以很简单,我用这个函数得到我的文件名。现在它正确返回。如何使用Swift 3删除此文件?我如何读取像UIImageJPEGRepresentation这样的图像?

let image_data = UIImageJPEGRepresentation(self.commons.correctlyOrientedImage(image: self.imageSelected.image!), 0.5)

我做了以下工作,它不工作

let filename = getDocumentsDirectory().appendingPathComponent("l.png")
let fileManager = FileManager.default
var filePath = filename
// Check if file exists

if fileManager.fileExists(atPath: filePath.absoluteString) {
    // Delete file
    try fileManager.removeItem(atPath: filePath.absoluteString)
} else {
    print("File does not exist")
}

我这样保存文件

let filename = getDocumentsDirectory().appendingPathComponent("COPY111.PNG")
               try? image_data?.write(to: filename)

但我不能把它从下面提供的答案中删除。

vof42yt1

vof42yt11#

删除文件有几行:

do {
    try FileManager.default.removeItem(at: fileName)
} catch let error as NSError {
    print("Error: \(error.domain)")
}

下面是将其设置为imageView的代码:

if let image = UIImage(contentsOfFile: fileName) {
   imageView.image = image
}
o2rvlv0m

o2rvlv0m2#

试试这个,删除文件

let fileNameToDelete = "myFileName.txt"
    var filePath = ""

    // Fine documents directory on device
    let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let documentDirectory = paths[0]
    filePath = documentDirectory.appendingFormat("/" + fileNameToDelete)

    do {
        let fileManager = FileManager.default

        // Check if file exists
        if fileManager.fileExists(atPath: filePath) {
            // Delete file
            try fileManager.removeItem(atPath: filePath)
        } else {
            print("File does not exist")
        }
    }
    catch let error as NSError {
        print("An error took place: \(error)")
    }

来源:Delete File Example in Swift

镜像加载

let imageData = UIImageJPEGRepresentation(image)!
let docDir = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let imageURL = docDir.appendingPathComponent("tmp.jpeg")
try! imageData.write(to: imageURL)

let newImage = UIImage(contentsOfFile: imageURL.path)!
daupos2t

daupos2t3#

您可以将删除代码放在DispatchQeue.main.async中,如下所示:

if fileManager.fileExists(atPath: filePath.absoluteString) {
    // Delete file
        try fileManager.removeItem(atPath: filePath.absoluteString)
}
else {
    print("File does not exist")
}

相关问题