Your issue is that URL(string:) expects a valid URL with a scheme (like file://), but you're passing a file path directly.
It is similar to the following error:ErrorDomain = NsCocoaErrorDomain & ErrorCode = 4
Instead, you should use URL(fileURLWithPath:) for file paths. Here's the fixed code:
var tempString = String()
for Rezept in alleRezepte {
tempString += "\(Rezept.name), \(Rezept.description), \(Rezept.nutrients), \(Rezept.whatToDo)\n"
}
if let dirs = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first {
let path = dirs.appending("/rezepte.csv")
let url = URL(fileURLWithPath: path)
do {
try tempString.write(to: url, atomically: true, encoding: .utf8)
print("Daten gesichert")
} catch {
print("Error saving file: \(error)")
}
}
Topic:
Programming Languages
SubTopic:
Swift
Tags: