func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
}
Run Code Online (Sandbox Code Playgroud)
所以简单地说,我使用该函数获取我的文件名.它现在正确返回,如何使用Swift 3删除此文件?我怎么能像这样读回图像UIImageJPEGRepresentation?
let image_data = UIImageJPEGRepresentation(self.commons.correctlyOrientedImage(image: self.imageSelected.image!),0.5)
Run Code Online (Sandbox Code Playgroud)
我做了以下,它没有工作
Run Code Online (Sandbox Code Playgroud)let filename = getDocumentsDirectory().appendingPathComponent("l.png") letfileManager = FileManager.default var filePath = filename //检查文件是否存在
Run Code Online (Sandbox Code Playgroud)if fileManager.fileExists(atPath: filePath.absoluteString) { // Delete file try fileManager.removeItem(atPath: filePath.absoluteString) } else { print("File does not exist") }
我保存这样的文件
Run Code Online (Sandbox Code Playgroud)let filename = getDocumentsDirectory().appendingPathComponent("COPY111.PNG") try? image_data?.write(to: filename)
但我无法从下面提供的答案中删除它
K. *_*hał 14
有一行删除文件:
do {
try FileManager.default.removeItem(at: fileName)
} catch let error as NSError {
print("Error: \(error.domain)")
}
Run Code Online (Sandbox Code Playgroud)
这里是将其设置为imageView的代码:
if let image = UIImage(contentsOfFile: fileName) {
imageView.image = image
}
Run Code Online (Sandbox Code Playgroud)
试试这个.希望它能工作.删除文件
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)")
}
Run Code Online (Sandbox Code Playgroud)
资料来源: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)!
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9541 次 |
| 最近记录: |