,swift 4如何通过方法参数传递 Decodable Struct
并在 JSONDecoder()
中解析它?错误:
无法用类型的参数列表调用'解码'(可解码, 来自:数据)'
struct JsonRespons: Codable {
let uid: String
let msisdn: String
let APK: String
let fname: String
let lname: String
}
struct JsonResponsError: Decodable {
let uid: String
let error: String
}
extension UIView {
func phoneAuth(serverApi path:String, jsonStruct:Codable){
let jsonUrlString = Globals.JOSN_API_URL + path
guard let url = URL(string: jsonUrlString) else {
return
}
URLSession.shared.dataTask(with: url) { (data, response, err) in
guard err == nil else {
return
}
guard let data = data else { return }
do {
let result = try JSONDecoder().decode(jsonStruct.self, from: data)
self.handleJsonResult(resalt: result as AnyObject)
} catch let jsonErr {
print("Error serializing json:", jsonErr)
}
}.resume()
}
func handleJsonResult(resalt:AnyObject){
print(resalt)
}
}
在地标的继承列表中添加代码触发了一个自动符合,该符合满足所有协议要求,可编码和解码:
您可以使用Codable
struct Landmark: Codable {
var name: String
var foundingYear: Int
// Landmark now supports the Codable methods init(from:) and encode(to:),
// even though they aren't written as part of its declaration.
}
替代解决方案是
func phoneAuth(serverApi path: String, Completion block: @escaping ((Data) -> ())) {
URLSession.shared.dataTask(with: URL(string: url)!) { (data, res, err) in
if let d = data {
block(d)
}
}.resume()
}
调用方法
phoneAuth(serverApi: "yourUrl") { (data) in
do {
let result = try JSONDecoder().decode(YourDecodable.self, from: data)
} catch let jsonErr {
print("Error serializing json:", jsonErr)
}
}
您不必将其作为参数传递,您可以像以下那样实现解码
extension UIView {
func phoneAuth(serverApi path:String){
let jsonUrlString = Globals.JOSN_API_URL + path
guard let url = URL(string: jsonUrlString) else {
return
}
URLSession.shared.dataTask(with: url) { (data, response, err) in
guard err == nil else {
return
}
guard let data = data else { return }
do {
let result = try JSONDecoder().decode(JsonRespons.self, from: data)
self.handleJsonResult(resalt: result as AnyObject)
} catch let jsonErr {
print("Error serializing json:", jsonErr)
}
}.resume()
}