2017-02-24 163 views
0
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 */} 

        } 

     } 
+0

见http://stackoverflow.com/questions/27327067/append-text-or-data-to-text-file-in-swift的信息上添加文本文件。 – rmaddy

回答

3

问题只是你一个误解:你似乎想象字符串的write方法追加到现有文件,而事实并非如此。它取代了文件的内容。

因此,您的代码正常工作。文本被写入文件,每次你说text.write...。 “问题”是这条线:

text = "\n" 
do{try text.write(to: path!, atomically: true, encoding: String.Encoding.utf8)} 

...用一个换行替换文件中的所有内容。而且,由于这是最后一行,所以我们完成时就是文件的状态。

+0

有没有办法追加到现有的文件?这就是我想要做的,最终 –

+0

当然,只需搜索“iOS文本文件追加”或类似的。 – matt

+0

或将所有内容累积到一个字符串中,然后将该字符串写出一次。而不是每次都设置“文本”,每次追加到“文本”;然后在一个文件中写入'text',最后一次。 – matt

-1

试试这个

let file = "file.txt" 
let text = "text content" 

if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first { 
    let path = dir.appendingPathComponent(file) 
    do { 
     try text.write(to: path, atomically: false, encoding: String.Encoding.utf8) 
    } 
    catch {} 
} 
+0

请解释问题中代码的错误,并解释您的答案如何解决问题。 – rmaddy