Reputation: 21
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Save data to file
let path = Bundle.main.path(forResource: "Test", ofType: "txt")
let fileURL = URL(fileURLWithPath: path!)
let text = "write this\n and this"
do {
try text.write(to: fileURL, atomically: true, encoding: String.Encoding.utf8)
} catch {
print("error")
}
}
}
I want to put the text into the txt file which I already put in the project folder, but after running the code, the Test.txt file is still empty.
Upvotes: 1
Views: 3037
Reputation: 5303
Please check out the documentation link above. There are a couple of places you can write files, this is just one of them:
let userDocumentsFolder = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let path = userDocumentsFolder.stringByAppendingPathComponent("Test.txt")
let fileURL = URL(fileURLWithPath: path)
let text = "write this\n and this"
do {
try text.write(to: fileURL, atomically: true, encoding: String.Encoding.utf8)
} catch {
print("error")
}
Upvotes: 2