【发布时间】:2019-08-09 08:07:56
【问题描述】:
我必须从 Alamofire 获取一些 json 并将它们保存到我制作的不同结构中,但我找不到为我需要发出的所有请求创建一种方法的方法。这是我的方法
func fetchData(url: String, parameters: [String : Any], finished: @escaping (EmployeeCompositionApp) -> Void) {
Alamofire.request(url,
method: .post,
parameters: parameters).responseJSON(completionHandler: { response in
guard response.result.error == nil else {
print("Error en la petición a Alamofire:\n \(String(describing: response.result.error))")
return
}
guard let json = response.result.value as? [String : Any] else {
if let error = response.result.error {
print("Error: \(error.localizedDescription)")
}
return
}
do {
let decoder = JSONDecoder()
let rawData = try JSONSerialization.data(withJSONObject: json, options: [])
let dataObject = try decoder.decode(EmployeeCompositionApp.self, from: rawData)
finished(dataObject)
} catch let error {
print("Error")
}
})
}
但是当我尝试将EmployeeCompositionApp 替换为Any 或任何其他泛型类型以便我可以将其与其他对象一起使用时,Xcode 会说
Cannot invoke 'decode' with an argument list of type '(Any, from: Data)'
我该怎么做?
【问题讨论】:
-
您应该使用符合
<T:Codable>或<T:Decodable>的类型
标签: swift function methods alamofire decoding