我每次启动应用程序时都试图覆盖现有文件。我试过两件事都不起作用。
1)我试图创建从在线服务器下载的文件名相同,但文件中的数据没有更新,我的代码是..
let documentsUrl:URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
let destinationFileUrl = documentsUrl.appendingPathComponent("Splash.text")
let fileURL = URL(string:(defaults.object(forKey: "MainAddress") as! String).appending(filedownloadLink)
print("proper url = \(String(describing: fileURL))")
let sessionConfig = URLSessionConfiguration.default
let session1 = URLSession(configuration: sessionConfig)
print("splash file url \(destinationFileUrl)")
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)")
}
do {
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()
2)然后我尝试在创建之前检查文件,如果它存在,那么我将其删除。但是一旦文件被删除,就不会打开文件" splash.text"不存在。下面是代码
do{
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let url = URL(fileURLWithPath: path)
let filePath = url.appendingPathComponent("Splash.text").path
let fileManager1 = FileManager.default
if fileManager1.fileExists(atPath: filePath) {
print("FILE AVAILABLE")
try fileManager1.removeItem(atPath: filePath)
} else {
print("FILE NOT AVAILABLE")
}
}
catch let error as NSError {
print("An error took place: \(error)")
}
在此代码之后,我调用了方法1的代码。我不确定为什么不再为第二种方法创建它,或者为什么它不会在第一种方法中覆盖它。