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

API未返回序列化JSON输出,如何在Xcode中获取序列化JSON?

Hey there! Let's work through getting that serialized JSON response from your login API in Xcode. Since you mentioned Postman works but your Swift code isn't showing the output, let's break down the solution step by step.

First, Fix Your URL Format

Notice your URLs have a double slash (//) after the port number—this might cause unexpected parsing issues. Clean them up to use a single slash:

let login_url = "http://192.168.100.11:9000/users/authenticate"
let checksession_url = "http://192.168.100.11:9000/users/authenticate"

Step 1: Handle App Transport Security (ATS)

iOS blocks HTTP requests by default, so you need to add an exception for your local API in Info.plist:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>192.168.100.11</key>
        <dict>
            <key>NSIncludesSubdomains</key>
            <true/>
            <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
    </dict>
</dict>

This is safer than allowing all arbitrary loads, but you can use NSAllowsArbitraryLoads for quick testing if needed.

Step 2: Implement the Network Request & JSON Serialization

Here’s a complete example you can drop into your loginViewController.swift—it matches how Postman sends requests, handles errors, and serializes the JSON response:

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

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

    // Setup the login request
    guard let loginUrl = URL(string: "http://192.168.100.11:9000/users/authenticate") else {
        print("Invalid login URL")
        return
    }

    let loginParams: [String: Any] = [
        "username": username,
        "password": password
    ]

    // Convert params to JSON data
    guard let jsonData = try? JSONSerialization.data(withJSONObject: loginParams) else {
        print("Failed to convert parameters to JSON")
        return
    }

    var request = URLRequest(url: loginUrl)
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type") // Match Postman's Content-Type
    request.httpBody = jsonData

    // Execute the request
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        // Handle network errors first
        if let error = error {
            print("Network error: \(error.localizedDescription)")
            return
        }

        // Validate HTTP response status code
        guard let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) else {
            print("Invalid response or non-success status code")
            if let httpResponse = response as? HTTPURLResponse {
                print("Status code received: \(httpResponse.statusCode)")
            }
            // Debug raw response if needed
            if let data = data, let rawString = String(data: data, encoding: .utf8) {
                print("Raw error response: \(rawString)")
            }
            return
        }

        // Validate we received data
        guard let responseData = data else {
            print("No data returned from API")
            return
        }

        // Serialize JSON data to a dictionary
        do {
            if let serializedJSON = try JSONSerialization.jsonObject(with: responseData, options: .allowFragments) as? [String: Any] {
                // Success! You have your serialized JSON
                print("Serialized JSON Response: \(serializedJSON)")

                // Access specific values (e.g., auth token)
                if let authToken = serializedJSON["token"] as? String {
                    print("Received auth token: \(authToken)")
                    // Update UI on main thread (critical for UI changes)
                    DispatchQueue.main.async {
                        // Navigate to home screen or show success message here
                    }
                }
            }
        } catch {
            print("Failed to serialize JSON: \(error.localizedDescription)")
            // Debug raw response string if serialization fails
            if let rawString = String(data: responseData, encoding: .utf8) {
                print("Raw response string: \(rawString)")
            }
        }
    }

    task.resume()
}

Key Things to Check

  • Match Postman’s Request Format: If your API expects x-www-form-urlencoded instead of JSON, adjust the request body and Content-Type header to application/x-www-form-urlencoded.
  • Debug Raw Responses: If JSON serialization fails, printing the raw string will help you spot if the API is returning non-JSON data (like an error page).
  • Main Thread for UI: Always wrap UI updates in DispatchQueue.main.async—network tasks run in the background, so you can’t update UI directly from there.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:24:08