2017-02-24 170 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