Skip to content

Instantly share code, notes, and snippets.

@mtackes
Last active August 29, 2015 14:09
Show Gist options
  • Save mtackes/68f901268dfb11167b23 to your computer and use it in GitHub Desktop.
Save mtackes/68f901268dfb11167b23 to your computer and use it in GitHub Desktop.
// Get the file manager
let fileManager = NSFileManager.defaultManager()
// Get the app's available documents directories
// For other options usable in iOS besides .DocumentsDirectory see:
// http://stackoverflow.com/questions/7268299/path-directory-usable-in-ios
let directoryURLs = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) as [NSURL]
// Cast to [NSURL] because it 'helpfully' gives back [AnyObject]
// iOS should only give you a single documents directory for your app
let documentsDirectory = directoryURLs[0]
// Append a specific file location you're interested in
let fileURL = documentsDirectory.URLByAppendingPathComponent("someFileName")
// Just because this is a quick example doesn't make us barbarians
var error: NSError?
// And use your favorite class's method to write to it. Similar in NSData, NSArray, NSString, etc.
NSData(base64EncodedString: "Just a quick test", options: .allZeros)?
.writeToURL(fileURL, options: .DataWritingAtomic, error: &error)
// Reading is just as easy
let data = NSData(contentsOfURL: fileURL, options: .allZeros, error: &error) // returns an optional
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment