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

使用Alamofire无法获取登录API序列化JSON输出求助

解决Alamofire无法序列化登录API JSON响应的问题

Hey there! Let's sort out why Alamofire isn't serializing the JSON from your login API—since it works fine in Postman, the fix is probably just a small tweak in your code or setup. Here's what you need to do:

1. First, Fix the API URL

Your current URL has a double slash (//) before users/authenticate—that's likely causing a request routing issue. Update it to the correct format:

let loginURL = "http://192.168.100.11:9000/users/authenticate"

2. Full Alamofire Request with Error Handling

Here's a tested, complete example for your LoginViewController.swift that handles JSON serialization and thorough error checking:

import Alamofire
import UIKit

class LoginViewController: UIViewController {

    @IBOutlet weak var usernameTextField: UITextField!
    @IBOutlet weak var passwordTextField: UITextField!

    @IBAction func loginButtonTapped(_ sender: UIButton) {
        // Validate input first
        guard let username = usernameTextField.text?.trimmingCharacters(in: .whitespaces), !username.isEmpty,
              let password = passwordTextField.text?.trimmingCharacters(in: .whitespaces), !password.isEmpty else {
            print("Please enter both username and password")
            return
        }

        // Setup request parameters matching your API requirements
        let parameters: [String: Any] = [
            "username": username,
            "password": password
        ]

        // Fixed API URL
        let loginURL = "http://192.168.100.11:9000/users/authenticate"

        // Send POST request with Alamofire
        AF.request(loginURL, method: .post, parameters: parameters, encoding: URLEncoding.default)
            .validate(statusCode: 200..<300) // Only process successful HTTP responses
            .responseJSON { response in
                switch response.result {
                case .success(let jsonData):
                    // Successfully serialized JSON!
                    print("Serialized JSON Output:")
                    print(jsonData)

                    // Convert to dictionary for further processing (e.g., extract token)
                    if let responseDict = jsonData as? [String: Any] {
                        let token = responseDict["token"] as? String
                        print("Login successful! Token: \(token ?? "No token found")")
                    }

                case .failure(let error):
                    // Debug the error thoroughly
                    print("Request failed with error: \(error.localizedDescription)")

                    // Print raw server response to see exactly what's coming back
                    if let rawData = response.data, let rawResponse = String(data: rawData, encoding: .utf8) {
                        print("Raw server response: \(rawResponse)")
                    }
                }
            }
    }
}

For cleaner, maintainable code, define a Codable model that matches your API's response structure, then use Alamofire's responseDecodable:

Step 3.1: Define the Response Model

Adjust this to match exactly what your API returns:

struct LoginResponse: Codable {
    let success: Bool
    let token: String
    let user: User?

    struct User: Codable {
        let id: Int
        let username: String
        // Add other fields your API returns (e.g., email, fullName)
    }
}

Step 3.2: Update the Alamofire Request

AF.request(loginURL, method: .post, parameters: parameters, encoding: URLEncoding.default)
    .validate()
    .responseDecodable(of: LoginResponse.self) { response in
        switch response.result {
        case .success(let loginResponse):
            print("Login successful! Token: \(loginResponse.token)")
            if let user = loginResponse.user {
                print("Welcome, \(user.username)!")
            }
        case .failure(let error):
            print("Parsing failed: \(error.localizedDescription)")
            // Print raw response for debugging
            if let rawData = response.data, let rawResponse = String(data: rawData, encoding: .utf8) {
                print("Raw server response: \(rawResponse)")
            }
        }
    }

4. Critical Setup Checks

  • ATS Permission: Since your API uses HTTP (not HTTPS), you need to allow insecure loads in your Info.plist:
    Add this snippet to your Info.plist file:
    <key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
    </dict>
    
  • Parameter Encoding: If your API expects JSON-formatted parameters instead of form data, replace URLEncoding.default with JSONEncoding.default in the request.
  • Network Connectivity: Ensure your iOS device/simulator is on the same local network as the API server (192.168.100.x subnet).

5. Debugging Tips

  • Print the raw response data in the failure case—this will reveal exactly what the server is sending back, even if it's not valid JSON.
  • Cross-check your Alamofire request with Postman's "Code" tab (Postman can generate Alamofire code directly to match your working Postman request).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:49:17