Asim Khan
Asim Khan

Reputation: 584

How to write data to a file in the projects directory?

I've some irregular huge amount of data in a text file, and by some crucial logics I've made it just like the way I needs. Now on every time the app loads the whole process if could be performed will cost deficiency up to remarkable extent. So what should I do in order to store this regular data for one permanent time, so then through that I should retrieve when and where I got need of it? Data is an unmodifiable pure in text format.

Upvotes: 0

Views: 62

Answers (1)

Joe Benton
Joe Benton

Reputation: 3753

Okay your question is very vague, but to give you a head start you can save data to a file and then read from it like this:

let file = "file.txt" //this is the file we will write to and read from it

let text = "some text" //your data/text

if let dir : NSString = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
    let path = dir.stringByAppendingPathComponent(file);

    //writing
    do {
        try text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding)
    }
    catch {
        /* error handling here */
    }

    //reading
    do {
        let textOut = try NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding)
        //use textOut - your content
    }
    catch {
        /* error handling here */
    }
}

Upvotes: 1

Related Questions