Overwrite text file in ios swift

Viewed 7617

I'm downloading a file from the internet at the start of application, and then saving it locally and using its data. i want the downloaded file to overwrite the previous file every single time at the start, but i'm unable to get the overwritten data, it keeps on displaying the previous file. and if i delete it by checking if it exists, then it gives an error " couldn’t be copied to “Documents” because an item with the same name already exists."". and if a don't create a new file while checking its existence then it give this error:

"Error took place while reading from file. Error description: %@ The file “Splashk.text” couldn’t be opened because there is no such file."

This is my code:

// 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)
}
1 Answers
Related