func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
}
因此,简单地说,我使用function.And获得文件名,它现在返回正确,我如何使用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 //检查是否存在文件 如果fileManager.fileExists(atPath: filePath.absoluteString) { //删除文件尝试fileManager.removeItem(atPath: filePath.absoluteString) },则{print(“文件不存在”)}}
我像这样保存文件
让文件名= getDocumentsDirectory().appendingPathComponent("COPY111.PNG")试试?image_data?.write(to: filename)
但我不能从下面提供的答案中删除它
发布于 2017-02-04 14:31:56
有删除文件的行:
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
}
发布于 2017-02-04 14:40:54
尝尝这个。希望work.To 删除一个文件
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)")
}
来源:http://swiftdeveloperblog.com/code-examples/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)!
发布于 2022-05-19 08:03:26
您可以将删除代码放在DispatchQeue.main.async
中,如下所示:
if fileManager.fileExists(atPath: filePath.absoluteString) {
// Delete file
DispatchQueue.main.async {
try fileManager.removeItem(atPath: filePath.absoluteString)
}
} else {
print("File does not exist")
}
https://stackoverflow.com/questions/42041405
复制相似问题