简体   繁体   中英

Swift 3 Writing to Text File

In my application, I am trying to add data to a text file in the document directory of the program called saveURL.txt so it can later be called and parsed. I have my code being

let fileName = "saveURL"
let DocumentDirURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)

let fileURL = DocumentDirURL.appendingPathComponent(fileName).appendingPathExtension("txt")
print("FilePath: \(fileURL.path)")

let writeString = "Write this text to the fileURL as text in iOS using Swift"
do {
    // Write to the file
    try writeString.write(to: fileURL, atomically: true, encoding: String.Encoding.utf8)
    print("past try writeString.write")
} catch let error as NSError {
    print("Failed writing to URL: \(fileURL), Error: " + error.localizedDescription)
}

var readString = "" // Used to store the file contents
do {
    // Read the file contents
    readString = try String(contentsOf: fileURL)
} catch let error as NSError {
    print("Failed reading from URL: \(fileURL), Error: " + error.localizedDescription)
}
print("File Text: \(readString)")

The output displayed in the console is

FilePath: /Users/mike/Library/Developer/CoreSimulator/Devices/752A5025-0AA0-4BE1-B70F-644A904F2D8A/data/Containers/Data/Application/0084AD99-63DB-439F-8427-DDDF161CFAC0/Documents/saveURL.txt
past try writeString.write
File Text: Write this text to the fileURL as text in iOS using Swift

Which is displaying output that it was infact stored, but when I go to check the file to see if it was actually appended to it, it is still blank. I've read all over that the swift files are meant to be read only and such but i've also seen examples that work but not in my program.

Here is code for write url in your text file.

func writeToFile(urlString: String)
{
    let file = "/saveURL.txt" //this is the file. we will write to and read from it

        if let dir = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true).first {
        let path = dir + file
        print(path)
        do {
            try urlString.write(toFile: path, atomically: false, encoding: String.Encoding.utf8)
        }
        catch {/* error handling here */}
    }
}

Hope this will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM