You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Alamofire发送POST请求后无法显示服务器响应问题排查

Troubleshooting Alamofire Response Closure Not Executing

Hey Vahid, let's break down why your print(Result) statement isn't running even though your server is sending a response. Here are the most likely causes and fixes based on your code:

1. You're Calling .resume() Unnecessarily

Alamofire's request() method automatically starts the request for you—you don't need to call .resume() at the end. This redundant call can cause unexpected behavior, including the request being canceled or the response closure not triggering properly.

Looking at your code, the final .resume() is the first thing you should remove:

// Remove this line entirely at the end of your request chain
.resume()

2. Request May Be Getting Deallocated Prematurely

If your request is created inside a short-lived object (like a ViewController that gets dismissed before the response arrives), and your closure captures a strong reference to self, you might create a retain cycle—or worse, the request gets deallocated before it can process the response.

To fix this, use a weak reference to self in your closure (if you reference self inside it) to avoid retain cycles:

Alamofire.request(urlString, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers)
    .responseJSON { [weak self] result in // Add [weak self] here
        print("Full response result: \(result)") // This will now run if the request completes
        guard let self = self else { return } // Unwrap weak self if you need to use it
        
        // Rest of your code here...
    }

3. Check for Response Serialization Failures (Even If Server Responds)

While you said the server returns a response, if the response isn't valid JSON, responseJSON will still trigger the closure—but result.result will be a .failure case. Your original print(Result) should still run, but if you're only checking Result.result.value, you might miss error cases.

Modify your initial print statement to log the entire result (including errors) to debug this:

print("Response Result: \(result)")
print("Response Error: \(result.result.error ?? "No error")")

4. Nested Request Logic Might Be Hiding Issues

Your code has a nested Alamofire request inside the first closure (when handling token expiration). Make sure:

  • The token variable is properly populated when you make the second request
  • The DataRe closure is correctly handling the response (if it's a completion handler, ensure it's not swallowing errors)

Modified Example Code

Here's a cleaned-up version of your request with the key fixes applied:

Alamofire.request(urlString, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers)
    .responseJSON { [weak self] result in
        print("Full Response Result: \(result)") // This will now execute
        
        guard let responseValue = result.result.value else {
            print("Request failed or no data returned: \(result.result.error ?? "Unknown error")")
            // Handle failure case here
            return
        }
        
        let resValue = JSON(responseValue)
        
        if resValue["error"].exists() {
            if resValue["error"] == "Authorization Required" {
                guard let pass = keychain.get("password") else {
                    // Handle missing password case
                    return
                }
                let get = LoginAndRegistration()
                get.getToken(userName: userName, passWord: pass) { tokenResult in
                    if tokenResult == "token got!" {
                        // Ensure `token` is accessible here
                        guard let validToken = token else { return }
                        Alamofire.request(urlString, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: [
                            "content-Type": "application/json",
                            "Authorization": "JWT \(validToken)"
                        ]).responseJSON { nestedResult in
                            guard let nestedResponseValue = nestedResult.result.value else {
                                print("Nested request failed: \(nestedResult.result.error ?? "Unknown error")")
                                return
                            }
                            let nestedResValue = JSON(nestedResponseValue)
                            DataRe(nestedResValue)
                        }
                    } else {
                        // Handle token refresh failure
                        DataRe(["message": "seque"])
                    }
                }
            }
        } else if resValue["Data"].exists() {
            DataRe(resValue)
        } else {
            DataRe(["message": "Something's Wrong"])
        }
    }

Final Checks

  • Verify that your urlString, parameters, and headers are correctly formatted (no typos in URLs or header keys)
  • Use Xcode's Network Inspector to confirm the request is sent and the server returns a valid HTTP status code (2xx range is ideal)
  • Ensure you're using a compatible version of Alamofire with your iOS SDK version

内容的提问来源于stack exchange,提问作者Vahid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:39:05