PIPIONE
对于读写,您应该使用一个可写的位置,例如文档目录。下面的代码演示如何读取和写入简单字符串。你可以在操场上测试它。SWIFT 3.x和SWIFT 4.0let file = "file.txt" //this is the file. we will write to and read from itlet text = "some text"
//just a textif let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let fileURL = dir.appendingPathComponent(file)
//writing do {
try text.write(to: fileURL, atomically: false, encoding: .utf8)
}
catch {/* error handling here */}
//reading do {
let text2 = try String(contentsOf: fileURL, encoding: .utf8)
}
catch {/* error handling here */}}SWIFT 2.2let file = "file.txt" //this is the file. we will write to and read from itlet text = "some text"
//just a textif let dir = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory,
NSSearchPathDomainMask.AllDomainsMask, true).first {
let path = NSURL(fileURLWithPath: dir).URLByAppendingPathComponent(file)
//writing do {
try text.writeToURL(path, atomically: false, encoding: NSUTF8StringEncoding)
}
catch {/* error handling here */}
//reading do {
let text2 = try NSString(contentsOfURL: path, encoding: NSUTF8StringEncoding)
}
catch {/* error handling here */}}SWIFT 1.xlet 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)}