LoginSignup
5
5

More than 5 years have passed since last update.

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

Last updated at Posted at 2016-08-10

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)
}
5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5