Help us understand the problem. What is going on with this article?

[swift2.2] NSFileManager よく使うファイル操作メソッド(保存、削除、取得、列挙)のswift版

More than 3 years have passed since last update.

http://qiita.com/yusuga/items/4698478a246245a0f6b4
上記記事のswift版です。swift3以降変わるとのことですが備忘録がてら写経。

FileManager.swift
// tmp/
func temporaryDirectory() -> NSString {
    return NSTemporaryDirectory()
}

// tmp/fileName
func temporaryDirectory(fileName: String) -> String {
    return temporaryDirectory().stringByAppendingPathComponent(fileName)
}

// Documents/
func documentDirectory() -> String {
    return NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first!
}

// Documents/fileName
func documentDirectory(fileName: String) -> String {
    return (documentDirectory() as NSString).stringByAppendingPathComponent(fileName)
}

// pathのファイルが存在しているか
func fileExists(path: String) -> Bool {
    return NSFileManager.defaultManager().fileExistsAtPath(path)
}

// pathのファイルがelapsedTimeを超えているか
func isElapsedFileModificationDate(path: String, elapsedTime: NSTimeInterval) throws -> Bool {
    if !fileExists(path) {
        return false
    }

    let attributes = try NSFileManager.defaultManager().attributesOfItemAtPath(path) as NSDictionary
    guard let date = attributes.fileModificationDate() else {
        return false
    }

    return elapsedTime < NSDate().timeIntervalSinceDate(date)
}

// directoryPath内のextensionName(拡張子)と一致する全てのファイル名
func fileNames(directoryPath: String, extensionName: String) throws -> [String] {
    let allFileName = try NSFileManager.defaultManager().contentsOfDirectoryAtPath(directoryPath)

    var hitFileNames = [String]()
    for fileName in allFileName {
        if (fileName as NSString).pathExtension == extensionName {
            hitFileNames.append(fileName)
        }
    }
    return hitFileNames
}

// pathのファイルを削除
func removeFilePath(path: String) throws{
    try NSFileManager.defaultManager().removeItemAtPath(path)
}
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away