Skip to content

Instantly share code, notes, and snippets.

@slav123
Created April 20, 2015 02:44
Show Gist options
  • Save slav123/f182c4f5281668b0b45f to your computer and use it in GitHub Desktop.
Save slav123/f182c4f5281668b0b45f to your computer and use it in GitHub Desktop.
read write from files in swift
let fileMgr = NSFileManager.defaultManager() func saveToFile(str: String, file: String) { var path = NSHomeDirectory().stringByAppendingPathComponent ("Documents").stringByAppendingPathComponent(file) Note Each app can write only to certain a certain folder inside the application home (for example, the Documents folder). The most common error is probably trying to create a file in the wrong place. var data = str.dataUsingEncoding(NSUTF8StringEncoding) var ok = fileMgr.createFileAtPath(path, contents: data, attributes: nil) } func retrieveFromFile(file: String) -> String? { var path = NSHomeDirectory().stringByAppendingPathComponent ("Documents").stringByAppendingPathComponent(file) if let data = fileMgr.contentsAtPath(path) { return NSString(data:data, encoding: NSUTF8StringEncoding) } return nil } func deleteFile(file: String) { var path = NSHomeDirectory().stringByAppendingPathComponent ("Documents").stringByAppendingPathComponent(file) var ok = fileMgr.removeItemAtPath(path, error: nil) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment