Alamofire下载目标错误处理

时间:2017-12-07 11:32:03

标签: ios swift error-handling download alamofire

我正在使用Alamofire 4从服务器下载文件,但有时服务器响应不包含标题文件名,我想处理此错误。 response.allHeaderFields["File-Name"] as! String Error?重写completion 如何捕获错误

func download(id: Int, completion: @escaping (_ url: URL?, _ error: Error?) -> Void) {
    print(id)
    var filePath: URL?
    var error: Error? = nil

    let destination: DownloadRequest.DownloadFileDestination = { _, response in
        let fileName = response.allHeaderFields["File-Name"] as! String
        let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let documentsURL = URL(fileURLWithPath: documentsPath, isDirectory: true)
        let fileURL = documentsURL.appendingPathComponent(fileName)

        return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
    }

    Alamofire.download("\(serviceUrl)/\(language)/\(_controller)/DownloadFile", parameters: ["id": id], to: destination).responseData {
        response in

        switch response.result {
        case .success(_):
            filePath = response.destinationURL
            break
        case .failure(let errorData):
            error = errorData
            break
        }

        completion(filePath, error)
    }
}

我正在使用:

  • Swift 4
  • Alamofire 4.6
  • iOS 11

0 个答案:

没有答案