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

时间:2016-04-04 18:16:24

标签: ios json swift file

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.

1 个答案:

答案 0 :(得分:1)

好的,你的问题非常模糊,但为了让你先行一步,你可以将数据保存到文件中,然后从中读取:

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 */
    }
}
相关问题