swift3.0 檔案操作
阿新 • • 發佈:2018-12-23
//儲存圖片的資料夾
varljFilePath:String = NSHomeDirectory() +"/Documents/"+"LJImageCache/"
/// 寫檔案 /// /// - Parameters: /// - fileName: 檔名稱 /// - data: 資料data /// - Returns: func writeFile(_ fileName:String , _ data:NSData) -> Bool{ //let filePath:String = NSHomeDirectory() + "/Documents/" + fileName.md5 //return data.write(toFile: filePath, atomically: true) if self.isExistsFile(path: ljFilePath) { guard let filePath : String = ljFilePath + fileName.md5 else{ return false } return data.write(toFile: filePath, atomically: true) } return false } //讀取檔案 -(根據路徑) func readFileFromCache(_ path:String) -> NSData?{ if self.isExistsFile(path: ljFilePath) { let ljpatch = ljFilePath + path.md5 var result:NSData? do{ result = try NSData(contentsOfFile: ljpatch, options: Data.ReadingOptions.uncached) }catch{ return nil } return result } return nil } //檢測資料夾是否存在,不存在則建立一個資料夾 func isExistsFile(path : String) -> Bool { let fileManager = FileManager.default let exist = fileManager.fileExists(atPath:path) if exist { //print("存在") return true }else{ //print("不存在") //不存在則建立一個資料夾 do{ try fileManager.createDirectory(at: NSURL(fileURLWithPath:path, isDirectory: true) as URL, withIntermediateDirectories: true, attributes: nil) }catch{ return false } return true } }