L
L
Lici2015-03-30 17:29:21
Objective-C
Lici, 2015-03-30 17:29:21

Swift: How to save results to txt files?

The program creates a string variable of the form:
First such text text such text text such text text
[enter, newline or other separator character]
Second such text text such text text such text text
[enter, newline or other separator character]
Third such text text such text text such text text
It is necessary to save each individual text as a separate txt file in the style 001.txt 002.txt 003.txt and so on. How to do it?
This code can generally make a file and read it:

let file = "file.txt"

if let dirs : [String] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String] {
    let dir = dirs[0] //documents directory
    let path = dir.stringByAppendingPathComponent(file);
    let text = "some text"
    
    //writing
    text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding, error: nil);
    
    //reading
    let text2 = String(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil)
    }

As far as I found out empirically, the creation of a file occurs when:
text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding, error: nil);
And let file = "file.txt" is purely its declaration in memory.
But if I don't know how many lines (and files) I will have, then how do I create files until I create them all for all lines?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Samoilov, 2015-03-30
@Lici

let text = "Первый такой текст текст такой текст текст такой текст текст\n Второй такой текст текст такой текст текст такой текст текст\n Третий такой текст текст такой текст текст такой текст текст"

let lines = split(text) { $0 == "\n" }

var counter = 0

for line in lines {
    if let dirs : [String] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String] {
        let dir = dirs[0] //documents directory
        let path = dir.stringByAppendingPathComponent("\(counter++).txt");

        //writing
        line.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding, error: nil);

        //reading
        let text2 = String(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil)
    }
}

Explain code?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question