0

I have a problem when write text to file document. This my source code:

 func getDocumentsDirectory() -> URL {
     let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
     return paths[0]
 }

 let fileName = getDocumentsDirectory().appendingPathComponent("LogFile.txt")

 do {
   try KML.soapRequest.xml.write(to: fileName, atomically: true, encoding: String.Encoding.utf8)
 } catch {
     print("Failed save")
 }

I want insert text to file "LogFile.txt", I am newbie in swift language.

Thanks for all the help.

1 Answers1

0

I found your problem here: Append text or data to text file in Swift

  • Will append to the text file if the file exists.
  • Will create a new file if the text file doesn't exist.

    class Logger {
    
    static var logFile: URL? {
        guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return nil }
    
        let formatter = DateFormatter()
            formatter.dateFormat = "dd-MM-yyyy"
        let dateString = formatter.string(from: Date())
        let fileName = "\(dateString).log"
    
        return documentsDirectory.appendingPathComponent(fileName)
        }
    
    static func log(_ message: String, functionName: String = #function, filename: String = #file, line: Int = #line) {
         guard let logFile = logFile else {
            return
         }
    
         let className = filename.components(separatedBy: "/").last
    
          let formatter = DateFormatter()
          formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS "
          let timestamp = formatter.string(from: Date())
          guard let data = ("[\(timestamp)]  [\(className ?? "")] \(functionName)\(line): \(message)" + "\n").data(using: String.Encoding.utf8) else { return }
    
          if FileManager.default.fileExists(atPath: logFile.path) {
             if let fileHandle = try? FileHandle(forWritingTo: logFile)          {
                    fileHandle.seekToEndOfFile()
                    fileHandle.write(data)
                    fileHandle.closeFile()
             }
            } else {
               try? data.write(to: logFile, options: .atomicWrite)
            }
         }
    }
    
Hiền Đỗ
  • 526
  • 6
  • 14