使用String的“write”实例方法将文本写入文件

时间:2017-02-24 03:49:54

标签: ios swift

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 个答案:

没有答案