Append new string to txt file in swift 2

早过忘川 提交于 2019-12-07 04:06:28

I think you must use NSFileHandle:

  let dir:NSURL = NSFileManager.defaultManager().URLsForDirectory(NSSearchPathDirectory.CachesDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask).last as NSURL
  let fileurl =  dir.URLByAppendingPathComponent("file.txt")

  let string = "\(NSDate())\n"
  let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!

  if NSFileManager.defaultManager().fileExistsAtPath(fileurl.path!) {
        var error:NSError?
        if let fileHandle = NSFileHandle(forWritingToURL: fileurl, error: &error) {
            fileHandle.seekToEndOfFile()
            fileHandle.writeData(data)
            fileHandle.closeFile()
        }
        else {
            println("Can't open fileHandle \(error)")
        }
  }
  else {
        var error:NSError?
        if !data.writeToURL(fileurl, options: .DataWritingAtomic, error: &error) {
            println("Can't write \(error)")
        }
  }

You can use the below method to append String to a file

func writeToFile(content: String, fileName: String) {

    let contentToAppend = content+"\n"
    let filePath = NSHomeDirectory() + "/Documents/" + fileName

    //Check if file exists
    if let fileHandle = NSFileHandle(forWritingAtPath: filePath) {
        //Append to file
        fileHandle.seekToEndOfFile()
        fileHandle.writeData(contentToAppend.dataUsingEncoding(NSUTF8StringEncoding)!)
    }
    else {
        //Create new file
        do {
            try contentToAppend.writeToFile(filePath, atomically: true, encoding: NSUTF8StringEncoding)
        } catch {
            print("Error creating \(filePath)")
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!