Topics

#46: NSFileManager 📂

Topics

NSFileManager is one of the primary ways you interact with the file system on iOS and OS X. Today we’ll look at both how to use it, as well as how to put some of the new Swift 2 features we’ve been learning about to real world use.

guard let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first else { return }

let logPath = documentsPath + "spaceship.log"
guard let logExists = fm.fileExistsAtPath(logPath) else { return }

do {
  let attributes = try fm.attributesOfItemAtPath(logPath)
  let createdAt = attributes[NSFileCreationDate]

  // > 5 minutes (in seconds) ago?
  if let created = createdAt where fabs(created.timeIntervalSinceNow) > 300 {
    try fm.removeItemAtPath(logPath)

      "[BEGIN SPACESHIP LOG]".writeToFile(
      logPath,
      atomically: false,
      encoding: NSUTF8StringEncoding,
      error: nil
    )
  }
} catch let error as NSError {
    print("Error: \(error.localizedDescription)")
}

Here we use NSFileManager to wipe out a log file if it's more than 5 minutes old:

First we use guard to make sure our documents directory is available.

Then, we create a path for our log file, and check that it exists.

Many of NSFileManager's functions are marked as throws, so we need a set of do/catch blocks.

Next we check when the log file was created.

We use another new Swift 2 feature, pattern matching, to do our age check on the optional inside the if statement.

Finally we try to remove the file, and replace it with a fresh, blank log.

We then use the catch statement to capture and print any errors that have been thrown.