我在应用程序启动时从Internet下载文件,然后在本地保存并使用其数据。我希望下载的文件在开始时每次都覆盖以前的文件,但我无法获取覆盖的数据,它会继续显示以前的文件。如果我通过检查它是否存在来删除它,那么它会给出一个错误"无法复制到“文档”,因为已存在具有相同名称的项目。""。如果在检查其存在的同时不创建新文件,则会出现此错误:
"从文件中读取时发生错误。错误说明:%@无法打开文件“Splashk.text”,因为没有这样的文件。"
这是我的代码:
// checking file existence
do{
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let url = URL(fileURLWithPath: path)
let filePath = url.appendingPathComponent("Splashk.text").path
let fileManager1 = FileManager.default
if fileManager1.fileExists(atPath: filePath) { // if available, delete the file and re create an empty file
print("FILE AVAILABLE")
try fileManager1.removeItem(atPath: filePath)
if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let path = dir.appendingPathComponent("Splashk.text")
// writing
do {
try text.write(to: path, atomically: true, encoding: String.Encoding.utf8)
}
catch {/* error handling here */}
}
} else { // if not available, create an empty file
print("FILE NOT AVAILABLE")
if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let path = dir.appendingPathComponent("Splashk.text")
// writing
do {
try text.write(to: path, atomically: true, encoding: String.Encoding.utf8)
}
catch {/* error handling here */}
}
}
}
catch let error as NSError {
print("An error took place: \(error)")
}
// getting the file path for destination file
let documentsUrl:URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!//try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) as URL!
let destinationFileUrl = documentsUrl.appendingPathComponent("Splashk.text")
let empId = self.defaults.object(forKey: "EmpId") as! String
// fileURL got the online url from which file is getting downloaded
let fileURL = URL(string:(defaults.object(forKey: "MainAddress") as! String).appending(download url)
let sessionConfig = URLSessionConfiguration.default
let session1 = URLSession(configuration: sessionConfig)
let request = URLRequest(url:fileURL!)
let task1 = session1.downloadTask(with: request) { (tempLocalUrl, response, error) in
if let tempLocalUrl = tempLocalUrl, error == nil {
// Success
if let statusCode = (response as? HTTPURLResponse)?.statusCode {
print("Successfully downloaded. Status code: \(statusCode)") // it is 200
}
do {
print("temp local url \(tempLocalUrl)")
try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
let fileManager = FileManager.default
// Check if file exists
} catch (let writeError) {
print("Error creating a file \(destinationFileUrl) : \(writeError)") //
}
} else {
print("Error took place while downloading a file. Error description: %@", error?.localizedDescription);
}
}
task1.resume()
//reading back from the destination file
do {
str = try String(contentsOf: destinationFileUrl, encoding: String.Encoding.utf8) as NSString
print("file text = \(str)")
parseXML()
} catch {/* error handling here */
print("Error took place while reading from file. Error description: %@", error.localizedDescription)
}
答案 0 :(得分:6)
尝试这行代码,我正在使用它并且它可以正常工作
let fileManger = FileManager.default
let doumentDirectoryPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
let filePath = doumentDirectoryPath.appendingPathComponent("Splashk.text")
if fileManger.fileExists(atPath: filePath){
do{
try fileManger.removeItem(atPath: filePath)
}catch let error {
print("error occurred, here are the details:\n \(error)")
}
}