I'm creating a Telegram bot on swift and vapor.
Created logFile.txt to store responses and outputs from people. The code works on mac. But when I build a project on Linux, I get this error: Error Domain=NSCocoaErrorDomain Code=4 "The file doesn’t exist."
//MARK:- Extension for String
extension String {
func appendLineToURL(fileURL: URL) throws {
try (self "\n").appendToURL(fileURL: fileURL)
}
func appendToURL(fileURL: URL) throws {
let data = self.data(using: String.Encoding.utf8)!
try data.append(fileURL: fileURL)
}
}
//MARK:- Extension for File data
extension Data {
func append(fileURL: URL) throws {
if let fileHandle = FileHandle(forWritingAtPath: fileURL.path) {
defer {
fileHandle.closeFile()
}
fileHandle.seekToEndOfFile()
fileHandle.write(self)
}
else {
try write(to: fileURL, options: .atomic)
}
}
}
Main body:
if update.message?.text != nil {
do {
let dir: URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last! as URL
let url = dir.appendingPathComponent("/logFile.txt")
try "\(format.string(from: date)); litl nis bot: \(update.message?.text ?? "Error")".appendLineToURL(fileURL: url.standardized as URL)
}
catch {
print("Something went wrong: \(error)")
}
Wanna create file in Linux with logs and ability to open it )
May be there is some problems with intermediate directories itself ? Please help
CodePudding user response:
I seem to recall encountering this problem when I first deployed to Linux after development on macOS. I solved it using this function that works on both:
func workingDirectoryURL(with components: [String] = []) throws -> URL {
let workPath = DirectoryConfiguration.detect().workingDirectory
if workPath == "" { throw InternalError.misc() }
var workPathURL = URL(fileURLWithPath: workPath)
components.forEach { component in workPathURL = workPathURL.appendingPathComponent(component) }
return workPathURL
}
You can then call it with something like:
workingDirectoryURL(with: ["path","relative","to","project","directory","logFile.txt"])
If you are looking simply to log events though, I would recommend looking at vapor's logging here: https://docs.vapor.codes/basics/logging/?h=log