0

I have a list of NSDictionary, and i want to save it in a file. I can save it in text file but i can't read it to [NSDictionary]

var text : [NSDictionary] = []

save file

let json = JSONSerializer.toJson(text)
try json.write(to: path, atomically: false, encoding: String.Encoding.utf8)

This is my list NSDictionary

[{ change = true; name = data1; },{ change = true; name = data2; }]
ZeMoon
  • 20,054
  • 5
  • 57
  • 98
Humyl
  • 143
  • 2
  • 9

3 Answers3

0
do {
        let text2 = try NSString(contentsOfURL: path, encoding: NSUTF8StringEncoding) // path give your file path
        print(text2)
    }
    catch {/* error handling here */}
}

Try this and tell is your problem solve or not .

Himanshu Moradiya
  • 4,769
  • 4
  • 25
  • 49
0

update code read file

let text2 = try String(contentsOf: path!, encoding: String.Encoding.utf8)
                    print(text2)
                    arrayFile = try JSONSerializer.toArray(text2) as! [NSDictionary]
                    print(arrayFile)

and print(text2)

{[{ 
change = true;
name = data1;
},{
change = true;
name = data2;
}]}
Humyl
  • 143
  • 2
  • 9
0

You can user plist for dictionary of data. Here is how we write data to plist file.

var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
var path = paths.stringByAppendingPathComponent("data.plist")
var fileManager = NSFileManager.defaultManager()
if (!(fileManager.fileExistsAtPath(path)))
{
    var bundle : NSString = NSBundle.mainBundle().pathForResource("data", ofType: "plist")
    fileManager.copyItemAtPath(bundle, toPath: path, error:nil)
}
data.setObject(object, forKey: "object")
data.writeToFile(path, atomically: true)

To read data from plist file,

var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
var path = paths.stringByAppendingPathComponent("data.plist")
let save = NSDictionary(contentsOfFile: path)