首页 > 解决方案 > 如何在 swift 4 和 Mac OS App 的可可中将数据(类型数据)转换为 zip 文件(类型文件)?

问题描述

我正在开发一个 mac os 应用程序,我必须将数据从服务器 API 转换为 zip 文件。API 以 Data 类型的编码格式返回一个 zip 文件本身(我正在从服务器获取一个 zip 文件),但我想将该数据转换为一个 zip 文件并希望存储在磁盘中。

我的功能:


func DownloadExamZip(){  
    let request = NSMutableURLRequest(url: NSURL(string: "http://localhost:5000/api/DownloadExamZip/EX0000018/ST000000195/874059")! as URL)  
    request.httpMethod = "GET"  
    let AuthorizationToken = "Hidden"  
    request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")  
    request.setValue(AuthorizationToken, forHTTPHeaderField: "Authorization")  
    let task = URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in  
        do {  
            guard data != nil else {  
                print("data is nil")  
                return  
            }  
            //Here i want to convert the type data to a zip file  

        }  
        catch {  
            print("Error -> \(error)")  
        }  
    }  
    task.resume()  
} 

谁能帮我把这些数据转换成一个 zip 文件。我还必须将该文件存储在磁盘中。

标签: macoscocoaswift4.1

解决方案


您可以使用write(to:options:)方法将数据写入特定 URL 的文件

    let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("yourfile.zip")
    do {
        try data.write(to: fileURL, options: .atomic)
    } catch {
        print(error)
    }

推荐阅读