【问题标题】:Overwrite text file in ios swift在ios swift中覆盖文本文件
【发布时间】:2017-12-04 07:20:36
【问题描述】:

我在应用程序启动时从 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)
}

【问题讨论】:

  • @DávidPásztor,接下来您只需将代码复制粘贴到 Xcode 中即可获得正确的格式,因为您的手动编辑不完整。

标签: ios swift file swift3 filepath


【解决方案1】:

试试这行代码,我正在使用它,它可以工作

let fileManager = FileManager.default
let documentDirectoryPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
let filePath = documentDirectoryPath.appendingPathComponent("Splashk.text")
if fileManager.fileExists(atPath: filePath){
    do{
        try fileManager.removeItem(atPath: filePath)
    }catch let error {
        print("error occurred, here are the details:\n \(error)")
    }
}

【讨论】:

  • 我已经在使用它来获取第二行中的路径检查我的代码。我的主要问题是当我试图访问这个文件时,它说文件不存在。
  • 你是说你的代码会到这一行吗? print("FILE NOT AVAILABLE")
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-10
  • 1970-01-01
  • 1970-01-01
  • 2023-03-11
  • 2014-10-22
  • 2016-05-25
  • 1970-01-01
相关资源
最近更新 更多