Cowboy Tech

iOS数据存储-沙盒数据

Sandbox path

var sp = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true)

if sp.count > 0{
    let url = NSURL(fileURLWithPath: "\(sp[0])/data.txt")
    print(url)
}

Write Data

let data = NSMutableData()
data.appendData("Hello Swift\n".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
data.writeToFile(url.path!, atomically: true)

Read Data - Method 1

do {
    let str1 = try NSString (contentsOfURL: url, encoding: NSUTF8StringEncoding)
    print(str1)
}catch{
    print(error)
}

Read Data - Method 2

let data = NSData(contentsOfFile: url.path!)
let str = NSString(data: data!, encoding: NSUTF8StringEncoding)
print(str)