我正在使用 Alamofire 4 从服务器下载文件但有时 server response doesn't contain header File-Name 我想处理这个错误 . How to catch error response.allHeaderFields["File-Name"] as! String 重写 Error? for 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)
    }
}

我正在使用:

  • 斯威夫特4

  • Alamofire 4.6

  • iOS 11