【发布时间】:2023-04-01 07:24:01
【问题描述】:
我正在将使用 Alamofire 1.3 的项目从 Swift 1.1 转换为 Swift 2.0。 因为这个版本的 Alamofire 与 Swift 2.0 不兼容,所以我切换到了 Alamofire 的最新版本(3.1.x)。
但是这破坏了代码,我现在收到错误消息
“不能调用非函数类型'NSHTTPURLResponse'的值?'”
这是由于我创建自定义“responseShop”Alamofire.Request 的扩展。
如何才能将此 Alamofire.Request 扩展正确转换为 Alamofire 3.x/Swift 2.0 语法?
extension Alamofire.Request {
func responseShop(options: NSJSONReadingOptions = .AllowFragments, var errorHandler:ProtocolWebServiceErrorHandler?, completionHandler: (ShopCallResult?, WebServiceErrorCode) -> Void ) -> Self {
objc_sync_enter(communicationLockObj)
return response(serializer: Request.JSONResponseSerializer(options: options), completionHandler: {
(request, response, JSON, error) in
log.verbose("\(JSON)")
//network error?
if let error = error {
//is it cancelled?
if error.code == -999 {
dispatch_async(dispatch_get_main_queue()) {
//call handler with cancelled code
completionHandler(nil, WebServiceErrorCode.requestCancelled)
}
objc_sync_exit(communicationLockObj)
return
}
dispatch_async(dispatch_get_main_queue()) {
errorHandler?.handleWebServiceError(WebServiceErrorCode.connectError, errorText : error.localizedDescription, request: request, json: JSON)
//call and supply org error
completionHandler(nil, WebServiceErrorCode.connectError)
}
objc_sync_exit(communicationLockObj)
return
}
if JSON == nil {
dispatch_async(dispatch_get_main_queue()) {
errorHandler?.handleWebServiceError(WebServiceErrorCode.jsonNil, errorText: nil, request: request, json: JSON)
//call and supply org error
completionHandler(nil, WebServiceErrorCode.jsonNil)
}
objc_sync_exit(communicationLockObj)
return
}
//api return error?
let callResult = ShopCallResult(json: JSON!)
if callResult.statusCode.failed {
dispatch_async(dispatch_get_main_queue()) {
errorHandler?.handleWebServiceError(callResult.statusCode, errorText: callResult.statusCode.localizedText, request: request, json: JSON)
completionHandler(callResult, callResult.statusCode)
}
objc_sync_exit(communicationLockObj)
return
}
//no error
dispatch_async(dispatch_get_main_queue()) {
completionHandler(callResult, WebServiceErrorCode.OK)
}
objc_sync_exit(communicationLockObj)
})
return self
}
}
【问题讨论】:
-
您不再需要指定 Json 序列化程序。尝试用
responseJSON{ response in debugPrint(response) }替换response看看这里的例子github.com/Alamofire/Alamofire/blob/master/Documentation/…