How to convert data(Type Data) into a zip file(Type File) in swift 4 and cocoa for Mac OS App?

723 views Asked by At

I am developing a mac os application where i have to convert the data from server API to a zip file. The API is returning a zip file itself(i am fetching a zip file from server) in encoded format of type Data, but i want to convert that data to a zip file and want to store in the disk.

My Function:


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()  
} 

Can anyone help me to convert that data into a zip file please. I also have to store that file in the disk.

1

There are 1 answers

0
Mubin Mall On

You can use write(to:options:) method to write your data to file at particular 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)
    }