var file = ""
var text = ""
var path: URL?
override viewDidLoad(){
super.viewDidLoad()
file = "test2.csv" //this is the file I will write to
if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
path = dir.appendingPathComponent(file)
do {
text = "Hello"
try text.write(to: path!, atomically: true, encoding: String.Encoding.utf8)
}
catch {/* error handling here */}
}
getInsightResult()
}
這段代碼在我的viewDidLoad()方法中完美地將「Hello」寫入「test2.csv」。但是,當我在一個名爲getInsightResult()的單獨方法中運行代碼摘錄時,我在viewDidLoad中調用該方法,正在寫入的文本是空白的。但是,當我打印出來的文本不是空的,而是顯示正確的文本。使用字符串的「寫入」實例方法將文本寫入文件
func getInsightResult() {
for x in 0...4{
for y in 0...4{
if(y != 3){
do{
let temp = arrayOfDataArrays[y]
text = String(temp[x])
print("Tester:\(temp[x])")
print("Text:" + text)
try text.write(to: path!, atomically: true, encoding: String.Encoding.utf8)
}
catch {/* error handling here */}
}
}
text = "\n"
do{try text.write(to: path!, atomically: true, encoding: String.Encoding.utf8)}
catch {/* error handling here */}
}
}
見http://stackoverflow.com/questions/27327067/append-text-or-data-to-text-file-in-swift的信息上添加文本文件。 – rmaddy