我正在尝试使用AlamofireObjectMapper
来发送请求的通用方法,其中输入是BasicMappable
(通用类型),输出是响应
func sendRequest<T>(endPoint: String,
parameters: Parameters,
method: HTTPMethod,
mappingObject: T.Type) -> T where T : BaseMappable {
var answer = T.self
Alamofire.request(applicationBaseURL + endPoint,
method: method,
parameters: parameters,
headers: nil)
.responseObject { ( response: DataResponse<T>) in
let data = response.result.value
answer = data as! T.Type
}
return answer as! T
}
所以我在VC中像这样使用这种方法:
let authResponse = requestHelper.sendRequest(endPoint: "/auth/users/create/",
parameters: params,
method: .post,
mappingObject: AnswerClass.self)
它构建良好。 但是,当我尝试发送请求时,出现了崩溃和错误
Could not cast value of type 'Travel.AuthController.AnswerClass.Type' (0x110186bf8) to 'Travel.AuthController.AnswerClass' (0x10de153b0).
2019-04-15 18:42:28.811494+0300 Travel[9951:596186] Could not cast value of type 'Travel.AuthController.AnswerClass.Type' (0x110186bf8) to 'Travel.AuthController.AnswerClass' (0x10de153b0).
我已经在VC中使用此功能
Alamofire.request(applicationBaseURL + "/auth/users/create/",
method: .post,
parameters: params,
headers: nil)
.responseObject { (response: DataResponse<AnswerClass>) in
let loginRespone = response.result.value
for error in loginRespone?.errors ?? [] {
print(error.detail)
print(error.source)
print(error.status)
}
效果很好
但是我想使这种方法在整个项目中通用化
如何正确转换这些类型的值,或者还有其他方法吗?
答案 0 :(得分:1)
谢谢@Kamran的帮助!
我的最终解决方案是:
class RequestHelper {
func sendRequest<T>(endPoint: String,
parameters: Parameters,
method: HTTPMethod,
mappingObject: T.Type,
completion: @escaping (_ response: T?, _ error: Error?) -> Void) where T : BaseMappable {
Alamofire.request(applicationBaseURL + endPoint,
method: method,
parameters: parameters,
headers: nil)
.responseObject { ( response: DataResponse<T>) in
switch response.result {
case .success(let value):
completion(value, nil)
case .failure(let error):
completion(nil, error)
}
}
}
}
答案 1 :(得分:0)
您需要使用completionHandler
来获取对象,
func sendRequest<T>(endPoint: String,
parameters: Parameters,
method: HTTPMethod,
mappingObject: T.Type,
completion: (T?, Error?) -> Void) {
Alamofire.request(applicationBaseURL + endPoint,
method: method,
parameters: parameters,
headers: nil)
.responseObject { ( response: DataResponse<T>) in
switch response.result {
case .success(let value):
completion(value, nil)
case .failure(let error):
completion(nil, error)
}
}
}