Answer the question
In order to leave comments, you need to log in
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)
}
Answer the question
In order to leave comments, you need to log in
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)
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question