将文件扩展名更改为.zip并从文档文件夹解压缩文件

时间:2018-10-17 07:44:19

标签: ios swift zip

使用Alamofire下载。文件正在应用程序文档文件夹中下载,附件中有.hub文件。 与将音频文件解压缩相比,我需要将.hub文件更改为.zip。 下载代码->

func getAudioFileFromServer(url: String, uuid: String) {

    let fileURL = URL(string: url)
    var request = URLRequest(url:fileURL!)
    request.setValue("myapikey", forHTTPHeaderField: "x-api-key")
    let destination = DownloadRequest.suggestedDownloadDestination()
    Alamofire.download(request, to: destination).validate().responseData { response in
        debugPrint(response)
        print(response.destinationURL!)
     }
}

来自服务器的响应->

file:///var/mobile/Containers/Data/Application/FC5F17C4-E8D3-4406-926A-97EB9447D87B/Documents/'bac6151ffbe74140a31408938c91fa33.hub'

2 个答案:

答案 0 :(得分:0)

要重命名文件,请使用moveItem(atPath:toPath:)的功能FileManager

要解压缩,最简单的方法是集成一些zip库:https://github.com/ZipArchive/ZipArchivehttps://github.com/marmelroy/Zip

答案 1 :(得分:0)

下载文件后,使用“ saveFileInDirectory”方法将扩展名更改为.zip,并使用成功块获取主文件。

 self.saveFileInDirectory(data: responce.result.value, fileName: "\(name!).zip", successblock: { (path) in
            print(path!)
            var filepath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0]
            let url = URL(fileURLWithPath: filepath)
            do {
                try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil)
                let done = SSZipArchive.unzipFile(atPath: path!, toDestination: url.path)
                if done{
                    let items = try FileManager.default.contentsOfDirectory(atPath: url.path)
                    print(items)
                    let destinationUrl = url.appendingPathComponent(items[0])
                    print(destinationUrl)
                }
            } catch let error as NSError{
                print(error)
            }
        })


func saveFileInDirectory(data: Data?, fileName: String?, successblock: @escaping (_ path: String?) -> Void) { // To add the image to cache for given identifier.
      let paths = NSSearchPathForDirectoriesInDomains( .documentDirectory, .userDomainMask, true)[0] as String
      let path = paths.appending("/\(fileName!)")
         if (FileManager.default.fileExists(atPath: path)) {
    try! FileManager.default.removeItem(atPath: path)
         } else {
    do {
        try data?.write(to: URL(fileURLWithPath: path, isDirectory: false))
        successblock(path)
    } catch {
        successblock(nil)
        print("Error while caching the data in cache folder.")
    }
}}