类方法要求"AFDataResponse<X>"符合可编码和可编码



我在这里读了很多问题,但没有答案帮助我解决这个错误,我的结构是可编码的,只使用String、Int和Double等数据类型。

我把它们放在单独的文件中

struct Feature : Codable {
var property: Properties?
var geometry: Geometry?
}
struct Properties : Codable {
let pk: Int
var title: String = ""
var name: String = ""
//var added: Date
}
struct Geometry : Codable {
var type: String = ""
var coordinates: [Double]?
}

这就是我得到错误的地方

CommunicationManager.request(endpoint: "url", onSuccess: { (response: AFDataResponse<Feature>) in
print(response)
})

这是我的方法的定义

import Alamofire
typealias APIHeaders = HTTPHeaders
typealias APIParameters = [String: Any]
enum APIMethod {
case get
case post
case delete
case put
fileprivate var value: HTTPMethod {
switch self {
case .get:
return HTTPMethod.get
case .post:
return HTTPMethod.post
case .delete:
return HTTPMethod.delete
case .put:
return HTTPMethod.put
}
}
}
enum APIEncoding {
case json
case url
fileprivate var value: ParameterEncoding {
switch self {
case .json:
return JSONEncoding.default
default:
return URLEncoding.default
}
}
}
class APIError {
var code: String?
var message: String?
init(message: String) {
self.code = nil
self.message = message
}
}
class APISessionManager: Session {
static let shared: APISessionManager = {
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 40
configuration.requestCachePolicy = .reloadIgnoringLocalAndRemoteCacheData
let manager = APISessionManager(configuration: configuration)
return manager
}()
}
class CommunicationManager {
class func request<T: Codable>(endpoint: String,
method: APIMethod = .get,
encoding: APIEncoding = .url,
parameters: APIParameters? = nil,
headers: APIHeaders? = nil,
onSuccess: @escaping (T) -> Void,
onFailure: ((APIError)-> Void)? = nil){
let request = APISessionManager
.shared
.request(endpoint,
method: method.value,
parameters: parameters,
encoding: encoding.value,
headers: headers)
request.responseJSON(completionHandler: { response in
guard response.error == nil else {
onFailure?(APIError(message: "error"))
return
}
guard let data = response.data else {
onFailure?(APIError(message: "error"))
return
}
guard let object = try? JSONDecoder().decode(T.self, from: data) else {
onFailure?(APIError(message: "error"))
return
}
onSuccess(object)
print(response)
})
}
}

我真的不知道该怎么办,人们问的所有问题都得到了解决,因为他们使用了Image或其他不使用协议Codable 的数据类型

在您所描述的API中,onSuccess闭包将采用Feature值,而不是AFDataResponse<Feature>值。

相关内容

  • 没有找到相关文章

最新更新