获取时间、Filemanager

355 阅读1分钟

1、字符串本地化: NSLocalizedString(text, tableName: "Localizations", bundle: Bundle.main, value: "", comment: "")

2、获取当前时间: func getCurrentTime(matter: String) -> String{

        let timeFormatter = DateFormatter()

        timeFormatter.dateFormat = matter

        return timeFormatter.string(from: Date())

}

3、获取当前时间是星期几

    func getNowWeekday() -> String {

        let calendar:Calendar = Calendar(identifier: .gregorian)

        var comps:DateComponents = DateComponents()

        comps = calendar.dateComponents([.year,.month,.day,.weekday,.hour,.minute,.second], from: Date())

        let weekDay = comps.weekday! - 1

        //星期

        let array = ["星期日","星期一","星期二","星期三","星期四","星期五","星期六"]

        return array[weekDay]

    }

4、获取某一路径下所有文件并返回urls

func getAllFiles(path: URL) -> [URL] {

    let contentsOfPath = try? FileManager.default.contentsOfDirectory(at:path, includingPropertiesForKeys: [URLResourceKey.isDirectoryKey], options: .skipsSubdirectoryDescendants)

    let folderList = (contentsOfPath?.sorted(by: { (url1, url2) -> Bool in

        let fileInfoDictionary1 = try? FileManager.default.attributesOfItem(atPath: url1.path)

               let fileInfoDictionary2 = try? FileManager.default.attributesOfItem(atPath: url2.path)

               let date1 = fileInfoDictionary1![FileAttributeKey.creationDate] as! Date

               let date2 = fileInfoDictionary2![FileAttributeKey.creationDate] as! Date

        return date1.compare(date2) == .orderedDescending

           })) ?? URL

    return folderList

}

5、清空某一文件夹

func removeFile(path: String){

    let files = FileManager.default.subpaths(atPath:path)

    for file in files ?? [] {

        do {

            try FileManager.default.removeItem(atPath: path + "/(file)") // 需要拼接路径!!

        } catch {

            print("remove item:(file)\n error:(error)")

        }

    }

}

\

6、删除文件夹中的某一个文件

func delete(url: URL) {

    do {

        try FileManager.default.removeItem(at: url)

    } catch  {

        print(error)

    }

}