swift文件操作
需要用到swift存储文件等操作,网上方法五花八门,搞来搞去,乱七八糟,很乱,于是,理了一下方法。
https://iuwe.cc/index.php/archives/79/
仅仅写我用到的几个方法,更多的方法不做讨论
首先我用 just库从服务器get到一个文件,我需要将它保存下来。
let manager = FileManager.default let baseUrl = NSHomeDirectory() + "/Documents/Amusic/" + self.filname let exist = manager.fileExists(atPath: baseUrl)
//将 文件地址存到 变量 exist中 if !exist{ //如果文件夹不存在,创建一个异常捕捉语句,创建文件夹 do { try manager.createDirectory(atPath: baseUrl, withIntermediateDirectories: true, attributes: nil) print("creat baseUrl Successful") } catch{ print("something wrong") } } //创建 文件夹 let filePath = baseUrl + "/" + self.filname + ".zip" let pathUrl:URL = URL.init(fileURLWithPath: filePath)
//将路径转换为URl形式 do{ try retfil.write(to: pathUrl) //将data直接写到文件里面 print("write successfully path:\(filePath)") }catch{ print("writefile error path:\(filePath)") }
2,删除某处文件
let manager = FileManager.default let folder = NSHomeDirectory() + "/Documents/Amusic" //要删除的文件夹 let files:[String]? = manager.subpaths(atPath: folder) //搜索文件夹下面所有文件 for file in files!{ //遍历文件夹下面的所有文件并删除 do{ try manager.removeItem(atPath: folder + "/\(file)")//删除 print("清理成功") }catch{ print("\(file) 删除失败") } }
3,解压zip压缩包,用到了zip库
let manager = FileManager.default let baseUrl = NSHomeDirectory() + "/Documents/Amusic/" + self.filname let filePath = baseUrl + "/" + self.filname + ".zip" let pathUrl:URL = URL.init(fileURLWithPath: filePath) let unzipUrl = URL.init(fileURLWithPath: baseUrl + "/out") do { try Zip.unzipFile(pathUrl, destination: unzipUrl, overwrite: true, password: "passwd",progress: { (Progress) ->() in print("extra:\(Progress)") }) } catch { print("Something went wrong") }