typealias jsonTaskCompletionHandler = (_ decodableObject: Decodable) -> Void
func getData(with url : String, completionHandler completion: @escaping jsonTaskCompletionHandler){
let newURL = URL(string: url)
self.session.dataTask(with: newURL!) { (data, _, _) in
guard let data = data else {return }
print(data)
do {
let jsonData = try JSONDecoder().decode(decodableObject.self, from: data)
return completion(decodableObject)
} catch {
print("decoding error")
}
}.resume()
}
相反,我正在硬编码'jsonStructure'以使其正常工作。
typealias jsonTaskCompletionHandler = (jsonStructure) -> Void
func getData(with url : String, completionHandler completion: @escaping jsonTaskCompletionHandler){
let newURL = URL(string: url)
self.session.dataTask(with: newURL!) { (data, _, _) in
guard let data = data else {return }
print(data)
do {
let jsonData = try JSONDecoder().decode(jsonStructure.self, from: data)
return completion(jsonData)
} catch {
print("decoding error")
}
}.resume()
}
}
@IBAction func getData(_ sender: UIButton) {
print("button press")
let networkCL = networkClient()
networkCL.getData(with: "someURL") { (objectThatConformsToCodable) in
print(objectThatConformsToCodable)
}
}
使问题更清楚。我想将任何符合可编码的数据结构/ Object传递给JSONDecoder()。decode并让完成处理程序返回JSON数据作为符合可编码的对象的实例,而不是我很难编码特定的数据类型进入
data = JSONDecoder.decode(dataType.self)
completion(data)
而我只想传入
data = JSONDecoder.decode(anyDataStructureThatIsCodable.self)
completion(data)
任何想法?提前谢谢!