Alamofire 响应来了,但没有响应 "Success case" 为什么?在 swift

Alamofire response coming but the same is not coming in "Success case" why? in swift

Json 响应即将到来但没有响应 Alamofire Success case 为什么?

代码:我在 APIReqeustManager Class 中使用 Alamofire,并在登录 swift 文件中调用其服务调用...所以这里 Json 响应即将到来,但没有响应 Alamofire Success case 为什么?

typealias requestCompletionHandler = (APIJSONReponse) -> Void

class APIReqeustManager: NSObject {

static let sharedInstance = APIReqeustManager()

 func serviceCall(param:[String:Any]?,
             method : HTTPMethod,
             loaderNeed : Bool,
             isTokenNeeded : Bool,
             header : [String : String]? = nil,
             url: String
             completionHandler:@escaping requestCompletionHandler) {

let params  = ["jsonrpc" : "2.0", "params" : param ?? nil] as [String : Any?]


sendRequestWithURL(url, method: method, needViewHideShowAfterLoading: needViewHideShowAfterLoading, queryParameters: queryParam, bodyParameters: (param != nil) ? (params as [String : AnyObject]?) : nil, headers: [String : String].self as? [String : String], vc: vc){
    resp in
    print(resp.response ?? "COULDN'T PARSE: \(String(data: resp.data ?? Data(), encoding: .utf8) ?? "")")

    ....
    
}


fileprivate func sendRequestWithURL(_ URL: String,
                                method: HTTPMethod,
                                retryCount: Int = 0,
                                completionHandler:@escaping 
requestCompletionHandler) {

let actualURL: String

var headerParams: HTTPHeaders?

if let headers = headers {
    headerParams = headers as? HTTPHeaders
}
print(headerParams)
print("Actual URL \(actualURL)")

AF.request(actualURL, method:method, parameters: bodyParameters,encoding: JSONEncoding.default, headers: headerParams)
    .responseJSON { response in

        print("Json response \(response)")//response coming
        switch response.result {
        case .success:
            let JSON = response.result as? NSDictionary
                print("JSON inside success: \(JSON)")//nil

                let wrappedResponse = APIJSONReponse.init(
                    data: response.data,
                    dict: response.result as! Dictionary<String, AnyObject>,//Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
                    response: response.response,
                    error: nil, rpcErrorData: nil)
                DispatchQueue.main.async(execute: {
                    completionHandler(wrappedResponse)
                })
        case .failure(let error):
            let error = error
            let wrappedResponse = APIJSONReponse.init(error: error, dataDict: [:])
            completionHandler(wrappedResponse)
            print(error.localizedDescription)
        }
}
}
}

现在在登录 swift 文件中调用它,如下所示

 func loginService() {

        let param = ["email" : "test@gmail.com",
                     "password": "12345678"]
        APIReqeustManager.sharedInstance.serviceCall(param: param, method: .post, url: "http://test.com/dev/login", isTokenNeeded: false){ [weak self] (resp) in
            
            print("login response \(resp)")

        }
    }

输出:

使用上面的代码,如果我打印 print("Json response: \(response)"),响应将是这样的

Json response: success({
result =     {
    status = A;
    token = "testtttttttt";
    userdata =         {
        "available_for_serivice" = N;
        "buy_review" = "<null>";
        city = test city;
        "company_name" = test;
       

对于相同的成功响应,如果我打印 inside Success case 然后 print("JSON inside success: (JSON)")

nil

Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

编辑:是这样的

class APIJSONReponse {
let data: Data?
let dict: Dictionary<String, AnyObject>?
let response: URLResponse?
var error: Error?
var message : String?
var rpcErrorData: ErrorDataModel?

init(response: URLResponse?,error: Error?,rpcErrorData: ErrorDataModel?){

我们来分析一下:

switch response.result {
case .success:
    let JSON = response.result as? NSDictionary
    print("JSON inside success: \(JSON)")//nil
    ...
case ...
}

因此在 switch 中,您正在测试 response.result。 那么如果输入success大小写,就意味着response.result匹配success,但是,怎么可能匹配NSDictionary呢? 这没有意义。

现在:

let JSON = response.result as? NSDictionary
print("JSON inside success: \(JSON)")//nil

如果 JSONnil,这意味着它不能被转换为 NSDictionary。所以这不是正确的类型。如前所述,这是一个 success 案例,而不是 NSDictionary.

所以稍后,当你写 response.result as! Dictionary<String, AnyObject> 时,as! 表示如果不可转换则崩溃,这是正常行为,因为它不可转换为 Dictionary<Sting, AnyObject>

改为:

switch response.result {
case .success(let json):
    guard let asDict = json as? [String: Any] else { 
        print("json isn't a Dictionary")
        return
    }
    let wrappedResponse = APIJSONReponse(data: response.data,
                                         dict: asDict
                                         response: response.response,
                                         error: nil, 
                                         rpcErrorData: nil)
    ...
case ...
}

现在,我不知道为什么要保留 response.dataasDict,这很奇怪。 我建议使用 Codable.