我需要请求服务器的url和请求正文,但响应将是一个zip文件我需要下载zip文件并使用它所以我使用以下方法但我需要知道如何保存文件和重用它 但得到以下错误
任务< 11E36FDA-1408-474D-B576-A222DEBA53B2>。< 3>。完成错误 - 代码:-1005
func performSyncRequest()
{
let documentsUrl = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).first
let url = syncUrl.prepareSyncURL()
var urlrequest = URLRequest(url: url)
urlrequest.httpMethod = "POST"
urlrequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
let requestBody = syncUrl.prepareRequestBody()
guard let httpBody = try? JSONSerialization.data(withJSONObject: requestBody, options: []) else { return }
urlrequest.httpBody = httpBody
do {
let convertedString = String(data: httpBody, encoding: String.Encoding.utf8)
print("Sync Request Body: \(convertedString!)")
}
let downloadTask = URLSession.shared.downloadTask(with: urlrequest, completionHandler: { url,response,error in
if error == nil {
//some code
do {
try FileManager.default.copyItem(at:url!, to: self.documentsUrl!)
print(self.documentsUrl!)
} catch (let writeError) {
print("error writing file \(self.documentsUrl!) : \(writeError)")
}
}
})
downloadTask.resume()
}
答案 0 :(得分:0)
这里的问题是在尝试下载zip文件时它们没有内容长度标题所以为了解决问题我使用了以下代码并且运行良好
urlrequest.addValue("", forHTTPHeaderField: "Accept-Encoding")