我在應用程序開始時從互聯網下載文件,然後在本地保存並使用其數據。我希望下載的文件在開始時每次都覆蓋前一個文件,但是我無法獲取覆蓋的數據,它會一直顯示前一個文件。如果我通過檢查它是否存在刪除它,那麼它會給出一個錯誤「無法複製到」Documents「,因爲具有相同名稱的項目已經存在。」「。如果a不創建新文件檢查它的存在,然後它給這個錯誤:在ios swift中覆蓋文本文件
"Error took place while reading from file. Error description: %@ The file 「Splashk.text」 couldn’t be opened because there is no such file."
這是我的代碼:
// 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)
}
@DávidPásztor,接下來,您可以簡單地複製粘貼代碼i n Xcode獲取正確的格式,因爲您的手動編輯不完整。 –